Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sql query from related tables

Tags:

mysql

I have 3 tables:

shopping:

id  buyer   fruit
1   1 [->]  2 [->]
2   2 [->]  2 [->]

fruits:

id  fruit
1   apple
2   banana

buyers:

id  buyer
1   ido
2   omri

I want to extract from the table of 'shopping' and put the values of the other tables ​​in the row. For example: Row number one in 'shopping' should look like this:

id  buyer   fruit
1   ido     banana
like image 699
ido bublil Avatar asked Sep 22 '12 18:09

ido bublil


People also ask

How get data from two related tables in SQL?

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 you create a query in several related tables?

Double-click the two tables that contain the data you want to include in your query and also the junction table that links them, and then click Close. All three tables appear in the query design workspace, joined on the appropriate fields. Double-click each of the fields that you want to use in your query results.


1 Answers

You just need to join the related tables on their respective IDs:

SELECT s.id, b.buyer, f.fruit 
FROM shopping s
JOIN fruits f ON s.fruit = f.id
JOIN buyers b ON s.buyer = b.id
like image 67
doublesharp Avatar answered Sep 29 '22 19:09

doublesharp