我有 2 张桌子:items
和items_purchased
. tag
名称和其他描述性信息在表items
中,每个项目的购买次数保存在items_purchased
表中。这些表是JOIN
在 item_id 上编辑的。
到目前为止,这是我的查询:
(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
? - 有没有更好的方法来执行此查询,而不是 20 条选择语句由 19
UNION ALL
秒连接?