2017-05-10 35 views
-3

發生了多少我有2個表,選定的食品table1的名稱 用戶在早餐,午餐,晚餐表2所選擇的食物,...SQL計數特定值從表1表2中

表1:

id name 
0 Apple 
1 watermelon 
2 Pear 
3 Peach 
4 Walnut 
. . 
200 Apricot 

表2:

id username breakfast lunch dinner Meal1 Meal2 Meal3 
0 Dave  apple  null Pear null null watermelon 
1 John  walnut  Peach Pear Apricot null apple 
. ....  ......  ..... .... ....... .... ..... 
900 Ray   walnut  Peach Pear Apricot null apple 

注:用戶不能選擇蘋果不止一次在兩餐。

我想看看有多少每個食物的廚師想這個客人:

apple 400 
Pear 399 
Peach 398 

我想:

SELECT breakfast, COUNT(*) AS value 
FROM table2 
WHERE breakfast != "" 
GROUP BY breakfast 
ORDER BY `value` DESC 
LIMIT 0 , 30 

,但它不是我想要的東西,如果用戶只想晚餐結果中不適用的食物名稱。 謝謝。

+0

應該嘗試做功課。 –

+0

看到正常化 – Strawberry

+0

@Strawberry謝謝你的時間。 – GOWB

回答

0

感謝Strawberry 它可以這樣做只是正常化表2

SELECT name, value 
FROM ( 
SELECT breakfast AS name, COUNT(*) AS value 
FROM table2 
WHERE breakfast != "" 
GROUP BY breakfast 
UNION 
SELECT lunch AS name, COUNT(*) AS value 
FROM table2 
WHERE lunch != "" 
GROUP BY lunch 
UNION 
SELECT dinner AS name, COUNT(*) AS value 
FROM table2 
WHERE dinner != "" 
GROUP BY dinner 
UNION 
SELECT meal1 AS name, COUNT(*) AS value 
FROM table2 
WHERE meal1 != "" 
GROUP BY meal1 
UNION 
SELECT candid5 AS name, COUNT(*) AS value 
FROM table2 
WHERE meal2 != "" 
GROUP BY meal2 
UNION 
SELECT meal3 AS name, COUNT(*) AS value 
FROM table2 
WHERE meal3 != "" 
GROUP BY meal3 
UNION 
SELECT meal4 AS name, COUNT(*) AS value 
FROM table2 
WHERE meal4 != "" 
GROUP BY meal4 
) AS mynewtablename 
GROUP BY name 
ORDER BY `mynewtablename`.`value` DESC 

希望他人Strawberry

學習並幫助別人。