[英]Join tables with separate rows [Query]
我過去兩個小時在網上環顧四周以解決我的問題,我有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
您可以使用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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.