我有以下数据库结构:
categories
-id
-name
videos
-id
-name
-category
pictures
-id
-name
-category
我想知道每个类别有多少视频和图片。
我尝试过从类别到图片和视频的简单左连接,但这会返回错误的值。是否可以仅在1个sql命令中获取每个的COUNT()?
答案 0 :(得分:0)
使用UNION应该可以工作:
SELECT c.name, count(*)
FROM (SELECT * FROM videos
UNION
SELECT * FROM pictures) AS all
LEFT JOIN categories c ON c.id=all.category
GROUP BY c.name
答案 1 :(得分:0)
试试这个:
SELECT
categories.name, COUNT(videos.id) AS video_count, COUNT(pictures.id) AS picture_count
FROM categories
INNER JOIN videos
ON categories.id = videos.category
INNER JOIN pictures
ON categories.id = pictures.category
GROUP BY categories.name;
答案 2 :(得分:0)
可以在同一个查询中获取两者。试试这个:
SELECT c.name,COUNT(DISTINCT v.id) as Videos,count(DISTINCT p.id) as Pictures
FROM categories c
LEFT JOIN videos v on v.category=c.id
LEFT JOIN Picture p on p.category=c.id
GROUP BY c.name