我在过去的 2 个小时里在网上环顾四周以解决我的问题,我有 2 张桌子与同一个用户。 我想连接两个表,同时不将它们合并到同一行中。
我尝试了多种连接表的方法。
例:
表 1:
ID| User | item
1 | Peter | Apple
2 | Peter | Grape
3 | John | Apple
4 | Smith | Lemon
表 2:
ID| User | Cars
1 | Smith | Mazda
2 | Peter | BMW
3 | Jamie | Apple
4 | Peter | Honda
我试图进行一个查询,向我显示一个人拥有的所有物品,这是 id 如何返回查询结果。
查询结果 im 试图获取:
ID| User | Belongings
1 | Peter | Honda
2 | Peter | BMX
3 | Peter | Apple
4 | Peter | Grape
您可以使用
union all
:
select id, user, item
from table1 t1
where user = 'Peter'
union all
select id, user, item
from table2 t2
where user = 'Peter';
如果要重新分配 id:
select (@rn := @rn + 1) as id, user, item
from ((select id, user, item
from table1 t1
where user = 'Peter'
) union all
(select id, user, item
from table2 t2
where user = 'Peter'
)
) p cross join
(select @rn := 0) params