SQL SELECT from multiple tables

tjcombos picture tjcombos · Sep 12, 2009 · Viewed 431.9k times · Source

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

Answer

Rowland Shaw picture Rowland Shaw · Sep 12, 2009
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