我有两个表类别和产品。类别表有id,name和product表有id,cat_id,name,details等。我需要一个mysql查询,它将选择属于每个类别的每个类别和产品总数,并按总计数排序结果。任何人都可以帮助我吗?
类别表
+----+------+
| id | name |
+----+------+
| 1 | cat1 |
| 2 | cat2 |
| 3 | cat3 |
+----+------+
产品表
+----+-------+--------+
| id | name | cat_id |
+----+-------+--------+
| 1 | prod1 | 1 |
| 2 | prod2 | 1 |
| 3 | prod3 | 3 |
| 4 | prod4 | 2 |
| 5 | prod5 | 2 |
| 6 | prod6 | 2 |
+----+-------+--------+
预期输出表
+----+------+-------+
| id | name | count |
+----+------+-------+
| 2 | cat2 | 3 |
| 1 | cat1 | 2 |
| 3 | cat3 | 1 |
+----+------+-------+
答案 0 :(得分:1)
我不知道小组是否有错误。但试试吧
select b.cnt,a.name from Category as a left join
(select count(*) as cnt,c.name,c.id from Product as p
left join Category as c.id = p.cat_id group by p.cat_id)
as b b.id = a.id order by cnt
答案 1 :(得分:1)
解决方案:
SELECT c.id category_id, c.name category_name, count( p.cat_id ) product_count
FROM categories c
INNER JOIN products p ON c.id = p.cat_id
GROUP BY p.cat_id
ORDER BY product_count DESC
和结果:
+-------------+---------------+---------------+
| category_id | category_name | product_count |
+-------------+---------------+---------------+
| 1 | cat1 | 7 |
| 2 | cat2 | 6 |
| 3 | cat3 | 3 |
+-------------+---------------+---------------+
没有LEFT JOIN