简体   繁体   中英

Mysql select with multiple foreign keys

I'm starting now with SQL and still have some basic difficulties.

Suppose I have three tables like:

suppliers ( sID: integer , sName: varchar, description: varchar); With sID as primary key

+-----+-----------+-------------+
| sID |   SName   | description |
+-----+-----------+-------------+
| 1   | Supplier1 | Desc1       |
| 2   | Supplier2 | Desc2       |
| 3   | Supplier3 | Desc3       |
| 4   | Supplier4 | Desc4       |
| ... | ...       | ...         |
+-----+-----------+-------------+

products ( pID: integer , pName: varchar, size: varchar); With pID as primary key

+-----+----------+------+
| pID |  pName   | size |
+-----+----------+------+
| 1   | Product1 | S    |
| 2   | Product2 | M    |
| 3   | Product3 | B    |
| 4   | Product4 | M    |
| ... | ...      | ...  |
+-----+----------+------+

menu ( sID: integer , pID: integer , cost: varchar); with sID and pID as foreign keys

+-----+-----+------+
| sID | pId | cost |
+-----+-----+------+
| 1   | 4   | 10   |
| 2   | 16  | 20   |
| 8   | 1   | 5    |
| 8   | 2   | 8    |
| ... | ... | ...  |
+-----+-----+------+

The only relation between suppliers and products is given by the menu table.

How can I select all suppliers that supply at least one product with size "M", AND, at least one product with size "B"?

I think that are simple tasks, but it's totally new for me and I really got stuck. Thanks for any help!

You can use aggregation and having :

select m.sid
from menu m join
     products p
     on m.pid = p.pid
group by m.sid
having sum(size = 'M') > 0 and
       sum(size = 'B') > 0;

Join the tables, filter the resultset so that you get only rows with products of the sizes that you want to aggregate on less number of rows and then group by supplier and set the condition in the HAVING clause:

select s.sid, s.name
from suppliers s 
inner join menu m on m.sid = s.sid
inner join products p on p.pid = m.pid
where p.size in ('M', 'B')
group by s.sid, s.name
having count(distinct p.size) = 2  

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