我在表格中有一些数据:
用户
user_id name
1 John
2 William
3 cindy
4 Julian
5 Monique
预订
user_id book_id
1 1
2 3
3 5
5 10
黑胶唱片
user_id vinyl_id
1 6
2 7
3 8
4 9
我想要一个能产生这个输出的SELECT语句:
user_id item_out
1 1
1 6
2 3
2 7
3 5
3 8
4 9
5 10
因此,按user_id和book_id / vinyl_id的顺序排列。这可能吗?
答案 0 :(得分:2)
您必须从两个单独的查询中获得UNION ALL
个结果:
SELECT u.user_id, book_id AS item_out
FROM user AS u
INNER JOIN books_out AS b ON u.user_id = b.user_id
UNION ALL
SELECT u.user_id, vinyl_id AS item_out
FROM user AS u
INNER JOIN vinyl_out AS v ON u.user_id = v.user_id
ORDER BY user_id, item_out
第一个查询返回books_out
表的结果,而第二个查询返回vinyl_out
表的结果。
注意: ORDER BY
子句适用于UNION ALL
操作生成的结果集。
答案 1 :(得分:0)
试试这个 如果有任何错误请评论。
select u.user_id,b.book_id as item_out from user u left join
books_out b on u.user_id = b.user_id
UNION ALL
select u.user_id,v.vinyl_id as item_out from user u left join
vinyl_out v on u.user_id = v.user_id
order by user_id;