Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL SELECT from multiple tables

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 
like image 924
tjcombos Avatar asked Sep 12 '09 20:09

tjcombos


People also ask

Can you SELECT from multiple tables in SQL?

In SQL we can retrieve data from multiple tables also by using SELECT with multiple tables which actually results in CROSS JOIN of all the tables. The resulting table occurring from CROSS JOIN of two contains all the row combinations of the 2nd table which is a Cartesian product of tables.

How do you SELECT data from multiple tables?

In SQL, to fetch data from multiple tables, the join operator is used. The join operator adds or removes rows in the virtual table that is used by SQL server to process data before the other steps of the query consume the data.

How do I SELECT multiple tables into one query?

From multiple tables To retrieve information from more than one table, you need to join those tables together. This can be done using JOIN methods, or you can use a second SELECT statement inside your main SELECT query—a subquery.


2 Answers

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 
like image 101
Rowland Shaw Avatar answered Sep 21 '22 08:09

Rowland Shaw


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; 
like image 38
Donnie C Avatar answered Sep 18 '22 08:09

Donnie C