2009-09-12 23 views
21

Tüm ürünleri müşteri1 ve müşteriler2'den nasıl alabilirim?SQL SELECT Birden çok tablodan

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 

Sonucu çok daha iyidir bu

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

Ok gibi olmalı! –

+0

Hangi veritabanı teknolojisini kullanıyorsunuz? –

cevap

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

+ 1 ** değil ** kullanılarak hazırlandı. * –

+0

s ikinci hattan ürün tablodur beyan bulunmaktadır. "P ürününden" – Keibosh

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

isim2 (ikinci yarısında ve NAME1) bu birliğin ilk yarısında bilinmeyen bir sütundur –

+0

MÜŞTERİ tablosunun hiçbir isim2 sütun var - belki istenilen çıktıyı maç için boş için takas, müşteri adı sütunlarını yeniden düzenlemek gerekir. Bir kez bittiğinde, çoğumuzla birlikte SOL LİDERLER için bir alternatif sunuyorsunuz. –

+0

@rexem, customer2 tablosunda –

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

eksik PRODUCT.pname kolon –

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
select pid, cid, pname, name1, null 
from product p 
inner join customer1 c on p.cid = c.cid 
union 
select pid, cid, pname, null, name2 
from product p 
inner join customer2 c on p.cid = c.cid 
+0

Okunabilirlik oy almak için anahtar - cevaplarınızı biçimlendirmeye bakın. –

+0

Denedim, ama yapacak :) –

İlgili konular