我是sql
的新手,并被赋予了加入3个表的任务。有人可以对这个问题有所了解sql
。
我有3张桌子,比如 表1
userID | username | password
1 user1 user1
2 user2 user2
表2
userID | order number | order quantity
2 101 100
表3
userID | name | address
1 John xxx
2 Will xxx
3 Peter xxx
结果表需要显示为:
UserID | username | name | address | order number | order quantity
1 user1 John xxxxx 0 0
2 user2 Will xxxxx 101 100
3 user3 Peter xxxxx 0 0
答案 0 :(得分:1)
您应该在某些列上使用LEFT JOIN
COALESCE
SELECT a.`userid`,
a.`username`,
c.`name`,
c.`address`,
COALESCE(b.`order number`, 0) `order Number`,
COALESCE(b.`order quantity`, 0) `order quantity`
FROM table1 a
LEFT JOIN table2 b
on a.userid = b.userid
LEFT JOIN table3 c
on a.userid = c.userid
基本上,LEFT JOIN
所做的是从左表中检索所有行,无论它是否与第二个表匹配。 COALESCE
处理null
值应该是什么样的。
答案 1 :(得分:0)
这将有助于
select
a.userID,
c.name,
c.address,
b.order_number,
b.order_quantity
from
table1 a
join table3 c
on a.userID=c.userID
join table2 b
on a.userID=c.userID
但是,您可能需要选择一本SQL书,因为这是一件非常简单的事情。