選擇最觀看項通過標籤的名字,我有2個表:items
和items_purchased
。 tag
名稱和其他描述性信息位於items
表格中,每個項目的採購數量保存在items_purchased
表格中。 item_id上的表格是JOIN
。與MySQL
這裏是我的查詢到目前爲止:
(select *, sum(purchaseyesno) as tots from items join items_purchased on items.item_id=items_purchased.item_id where tag = 'History' and deleted!=1 and pub_priv!=1 order by tots desc limit 1)
UNION ALL
(select *, sum(purchaseyesno) as tots from items join items_purchased on items.item_id=items_purchased.item_id where tag = 'Medicine' and deleted!=1 and pub_priv!=1 order by tots desc limit 1)
UNION ALL
(select *, sum(purchaseyesno) as tots from items join items_purchased on items.item_id=items_purchased.item_id where tag = 'Biology' and deleted!=1 and pub_priv!=1 order by tots desc limit 1)
//... more tags (20 in all) would follow
的問題是,與某些標籤的物品尚未所以查詢拋出的Column "item_id" cannot be null
錯誤購買。
這裏的示例表:
items | items_purchased |
item_id tag title | item_id purchaseyesno|
1 Biology DNA is cool | 1 1 |
2 Medicine Doctors | 2 1 |
3 Law Laws are cool| 4 1 |
4 Biology DNA NOT cool | 1 1 |
樣品結果:
item_id tag title tots
1 Biology DNA is cool 2
2 Medicine Doctors 1
3 Law Laws are cool 0
2個問題:
- 我怎樣才能排除這些
SELECT
語句之一,如果它的結果將是NULL
? - 是否有更好的方法來做到這一點查詢,而不是19個
UNION ALL
小號加入20條select語句?
你沒有標籤的主表? –
我可以但還沒有一個,我仍在考慮如何構建我的模式 –
使用聚合函數SUM沒有GROUP BY隱式地在所有行上組;選擇'*'會導致檢索到不確定的記錄(有關更多信息,請參見[手冊](http://dev.mysql.com/doc/en/group-by-hidden-columns.html))... can你顯示樣品表數據和樣品所需的結果? – eggyal