2015-11-09 60 views
1

這裏是我(簡化)表結構:MySQL查詢:如何

table: category_main 
id name 
------------- 
1 food 
2 vegetable 

table category_sub 
id id_catmain name 
--------------------- 
10 1   cake 
11 1   chocolate 
12 1   burger 
13 2   apple 
14 2   banana 

table images 
id id_catsub filename   views 
------------------------------------- 
1 10  cake1.jpg  11 
2 10  cake2.jpg  24 
3 10  cake3.jpg  65 
4 11  chocolate1.jpg 31 
5 11  chocolate2.jpg 62 
6 11  chocolate3.jpg 32 
7 11  chocolate4.jpg 58 
8 12  burger1.jpg  23 
9 12  burger2.jpg  43 
10 12  burger3.jpg  76 
11 13  apple1.jpg  29 
11 13  apple2.jpg  67 
11 14  banana1.jpg  78 

所需的輸出:

id name  total_views 
---------------------------- 
1 food  425 
2 vegetable 174 

,你可以看到我想要得到各主要類別的總的看法。 我目前正在運行的每個子類一個循環,但必須有一個更簡單,更快捷的方式:/

感謝

+1

查找到'SUM()'和'GROUP BY' – miken32

回答

3

LEFT JOIN +聚合將做的工作。

SELECT cm.id, cm.name, sum(images.views) as views 
FROM category_main as cm 
LEFT JOIN category_sub as cs ON cs.id_catmain = cm.id 
LEFT JOIN images ON images.id_carsub = cs.id 
GROUP BY cm.id 
ORDER BY views DESC; 

LEFT JOIN(而不是JOIN)會讓你確保你有所有類別列出即使在它沒有子類或圖像。如果您不希望列出空的類別,請使用JOIN

1
SELECT c.id AS id, c.name AS name, sum(i.views) AS total_views 
FROM category_main c, category_sub s, images i 
WHERE c.id=s.id_catmain and s.id=i.id_catsub 
GROUP BY c.id,c.name; 
1

只是加入了三個表,然後你可以總結由ID的分組的看法:

select cm.id, cm.name, sum(i.views) as total_views from 
category_main as cm inner join category_sub as cs on cm.id = cs.id_catmain 
inner join cs.id = i.id_catsub group by cm.id