简体   繁体   中英

mysql query with info from 3 different tables

I have an online store, and the products database is setup like below. What I want to do is to form a query that will print main categories and number of products inside them, ordered by fewest to most products. Is that possible without doing multiple queries?

Result should be like this:

maincat   products
melons    0
grapes    2
apples    4

Databases:

database: maincat
id   name
1    apples
2    grapes
3    melons

database: subcat
maincat_id  subcat_id  name
1           1          yellow apples
1           2          green apples
2           3          normal grapes
3           4          watermelons
3           5          honeydew melon

database: products
subcat_id   name
1           yellow apple 1
1           yellow 2
1           yellow 3
2           green apple 1
3           grape 1
3           grape 2
select m.name, count(p.subcat_id) as products
from maincat m
left join subcat s on s.maincat_id = m.id
left join products p on p.subcat_id = s.subcat_id
group by m.name

Yep it is possible. This is a very common case too.

What u need is JOIN on multiple tables.

See this link for a good explanation on how it works and which join u need: https://stackoverflow.com/a/38578/4218046

The explanation there is for 2 tables, but it works the same way for 3 tables.

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