简体   繁体   中英

How can I select rows from 3 tables with link table?

I have the following tables:

| Store            | Address | Category    | link             |
|   id             |   id    |   id        |   fk_categoryID  |
|   fk_addressID   |   city  |   category  |   fk_storeID     |

I want to select all stores with address that has category A.

I use this to find stores in a specific city:

SELECT a.name, b.street1, b.street2, b.city
FROM store a
JOIN address b ON b.id = a.fk_addressID
WHERE b.city = 'oslo'

Now I just need to add category criteria.

I can't remember how to do that. Adding another INNER or LEFT join for the link table works, but I get 7-10 rows for each store found.

Can anyone help me please?

Try the following:

SELECT s.id AS "Store ID", a.id AS "Address ID", a.city AS "City", c.category AS "Category" FROM store s
LEFT JOIN address a ON a.id = s.fk_addressID
LEFT JOIN link l on l.fk_storeID = s.id
LEFT JOIN category c on c.id = l.fk_categoryID
WHERE a.city = "oslo" AND c.category = "A";

Let me know if that helps!

EDIT

Recreated the schema on my computer, added some test data, ran the SQL and got the following:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM