と の 2 つのテーブルがitemsありitems_purchasedます。名前とその他のtag説明情報がitemsテーブルにあり、各アイテムの購入数がテーブルに保存されitems_purchasedます。テーブルはJOINitem_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ですか?UNION ALL19 sで結合された 20 の select ステートメントではなく、このクエリを実行するためのより良い方法はありますか?