SELECT from Multiple Tables

This statement is used to retrieve fields from multiple tables. To do so, we need to use join query to get data from multiple tables.

Let’s see the example for the select from multiple tables:

 SELECT orders.order_id, suppliers.name   

FROM suppliers  

INNER JOIN orders  

ON suppliers.supplier_id = orders.supplier_id  

ORDER BY order_id; 

    Let us take three tables, two tables of customers named customer1 and customer2 and the third table is product table.

    Customer1 table

    Cus_idName1
    1Jack
    2Jill

    Customer2 table

    Cus_idName2
    1Sandy
    2Venus

    Product table

    P_idCus_idP_name
    11Laptop
    22Phone
    3P1Pen
    4P2Notebook

    Example syntax to select from multiple tables:

    SELECT p. p_id, p.cus_id, p.p_name, c1.name1, c2.name2  
    
    FROM product AS p  
    
    LEFT JOIN customer1 AS c1  
    
    ON p.cus_id=c1.cus_id  
    
    LEFT JOIN customer2 AS c2  
    
    ON p.cus_id = c2.cus_id
    P_idCus_idP_nameP_nameP_name
    11LaptopJackNULL
    22PhoneJillNULL
    3P1PenNULLSandy
    4P2NotebookNULLVenus

    Comments

    Leave a Reply

    Your email address will not be published. Required fields are marked *