2009-09-12 81 views
21

如何獲取customers1和customers2的所有產品都包含其客戶名稱?來自多個表的SQL SELECT

customer1 table 
cid name1 
1 john 
2 joe 

customer2 table 
cid name2 
p1 sandy 
p2 linda 

product table 
pid cid pname 
1 1 phone 
2 2 pencil 
3 p1 pen 
4 p2 paper 

結果應該是這樣的

pid cid pname name1 name2 
1 1 phone john NULL 
2 2 pencil joe NULL 
3 p1 pen NULL sandy 
4 p2 paper NULL linda 
+0

確定這是好多了! – 2009-09-12 20:13:33

+0

你使用了哪些數據庫技術? – 2009-09-12 20:13:39

回答

42
SELECT p.pid, p.cid, p.pname, c1.name1, c2.name2 
FROM product p 
LEFT JOIN customer1 c1 ON p.cid = c1.cid 
LEFT JOIN customer2 c2 ON p.cid = c2.cid 
+2

對於**不**使用PRODUCT。* – 2009-09-12 20:22:04

+0

有聲明p是第二行的產品表。 「FROM product p」 – Keibosh 2013-08-19 18:12:19

3
SELECT `product`.*, `customer1`.`name1`, `customer2`.`name2` 
FROM `product` 
LEFT JOIN `customer1` ON `product`.`cid` = `customer1`.`cid` 
LEFT JOIN `customer2` ON `product`.`cid` = `customer2`.`cid` 
7
SELECT pid, cid, pname, name1, name2 
FROM customer1 c1, product p 
WHERE p.cid=c1.cid 
UNION SELECT pid, cid, pname, name1, name2 
FROM customer2 c2, product p 
WHERE p.cid=c2.cid; 
+0

name2是該聯盟前半部分中的未知列(以及後半部分中的name1) – 2009-09-12 20:20:03

+0

CUSTOMER表中沒有name2列 - 您需要重新排列客戶名稱列,交換空值以匹配期望的輸出。一旦完成,你確實提供了我們大多數人提出的左連接的替代方案。 – 2009-09-12 20:20:45

+0

@rexem在customer2表中有 – 2009-09-12 20:21:35

3
select p.pid, p.cid, c1.name,c2.name 
from product p 
left outer join customer1 c1 on c1.cid=p.cid 
left outer join customer2 c2 on c2.cid=p.cid 
+0

缺少PRODUCT.pname列 – 2009-09-12 20:21:32

1
SELECT p.pid, p.cid, p.pname, c1.name1, c2.name2 
FROM product AS p 
    LEFT JOIN customer1 AS c1 
     ON p.cid = c1.cid 
    LEFT JOIN customer2 AS c2 
     ON p.cid = c2.cid 
1
​​
+0

可讀性是獲得投票的關鍵 - 查看格式化您的答案。 – 2009-09-12 20:25:23

+0

試過了,但會做:) – 2009-09-12 20:38:42