联接具有单独行的表[查询]

时间:2019-02-08 23:39:50

标签: mysql sql phpmyadmin

过去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返回查询结果的方式。

查询结果试图获取:

ID| User  | Belongings
1 | Peter | Honda
2 | Peter | BMX
3 | Peter | Apple
4 | Peter | Grape

1 个答案:

答案 0 :(得分:0)

您可以使用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
相关问题