Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select data from three tables?

Tags:

sql

select

How can I write a SQL statement to select data from three tables?

like image 523
sadi Avatar asked Mar 14 '11 17:03

sadi


People also ask

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 can I get data from multiple tables in SQL?

SQL JOIN. A JOIN clause is used to combine rows from two or more tables, based on a related column between them.

How do you fetch data from three tables in SQL with join?

The syntax for multiple joins: SELECT column_name1,column_name2,.. FROM table_name1 INNER JOIN table_name2 ON condition_1 INNER JOIN table_name3 ON condition_2 INNER JOIN table_name4 ON condition_3 . . . Note: While selecting only particular columns use table_name.


1 Answers

Use a join

SELECT *
FROM table_1
JOIN table_2 ON (table_2.table_1_id = table_1.table_1_id)
JOIN table_3 ON (table_3.table_1_id = table_1.table_1_id)

This will require that each table has a table_1_id key and that there is an entry in each table.

You can use a LEFT JOIN if table_2 or table_3 may not have data but you still want to show the data from table_1

like image 184
Jim Avatar answered Sep 29 '22 15:09

Jim