views:

208

answers:

6

How can I get all products from customers1 and customers2 include their customer names?

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

Result should be like this

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
+1  A: 
SELECT `product`.*, `customer1`.`name1`, `customer2`.`name2`
FROM `product`
LEFT JOIN `customer1` ON `product`.`cid` = `customer1`.`cid`
LEFT JOIN `customer2` ON `product`.`cid` = `customer2`.`cid`
chaos
+1  A: 

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;

Donnie C
name2 is an unknown column in the first half of that union (and name1 in the second half)
Rowland Shaw
There's no name2 column in either CUSTOMER table - you need to rearrange the customer name columns, swapping for null to match the desired output. Once that's done, you do provide an alternative to the LEFT JOINs most of us came up with.
OMG Ponies
@rexem there is in the customer2 table
Rowland Shaw
@Rowland: You're right, thanks. Still, wish this hadn't been marked down.
OMG Ponies
Thanks for the constructive feedback, guys!
Donnie C
+1  A: 
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
Philippe Leybaert
Missing PRODUCT.pname column
OMG Ponies
+3  A: 
SELECT p.pid, p.cid, p.pname, c1.name1, c2.name2
FROM product
LEFT JOIN customer1 c1 ON p.cid = c1.cid
LEFT JOIN customer2 c2 ON p.cid = c2.cid
Rowland Shaw
+1 for **not** using PRODUCT.*
OMG Ponies
A: 
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
LukeH
A: 

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

rdkleine
Readability is key to getting votes - look into formatting your answers.
OMG Ponies
Tried, but will do :)
rdkleine