How to get all records from two tables?

时间:2022-03-24 22:14:33

Lets say we have two simple tables like:

可以说我们有两个简单的表,如:

**table1**                      **table2**
Nr   Color                      Id   Type
1    green                      43   metal
2    red                        52   glass
3    black                     
4    white 

What I want to retrieve in my query is:

我想在我的查询中检索的是:

Nr   Color   Id   Type
1    green   43   metal
2    red     52   glass
3    black
4    white

Please help me.

请帮帮我。

1 个解决方案

#1


1  

Its simply not possible, you need to do some trick here..

它根本不可能,你需要在这里做一些技巧..

select Nr, Color, Id, Type
from (select @counter1 := @counter1+1 as counter, Nr, Color
      from table1, (select @counter1 := 0) init) t1
left join (select @counter2 := @counter2+1 as counter, Id, Type
           from table2, (select @counter2 := 0) init) t2
using (counter)

Produce result

Nr   Color   Id   Type
1    green   43   metal
2    red     52   glass
3    black
4    white

But as comment suggest best practice is define relation between tables.

但是,评论建议最佳实践是定义表之间的关系。

#1


1  

Its simply not possible, you need to do some trick here..

它根本不可能,你需要在这里做一些技巧..

select Nr, Color, Id, Type
from (select @counter1 := @counter1+1 as counter, Nr, Color
      from table1, (select @counter1 := 0) init) t1
left join (select @counter2 := @counter2+1 as counter, Id, Type
           from table2, (select @counter2 := 0) init) t2
using (counter)

Produce result

Nr   Color   Id   Type
1    green   43   metal
2    red     52   glass
3    black
4    white

But as comment suggest best practice is define relation between tables.

但是,评论建议最佳实践是定义表之间的关系。