1
我在我的sqlite
數據庫中有一個inventory
表,其中包含列category
,name
和count
。我想過濾掉count
小於2的行,並將另一個category
行放在類別中的所有其他數據之前,以便更容易將它們存儲在GUI中的樹視圖中。具有相同條件的聯合結果
我的表中的數據是:
category name count
---------- ---------- ----------
fruit apple 4
fruit banana 3
fruit peach 2
meat pork 1
meat beef 1
vegetable spinach 5
vegetable carrot 2
和我做的是:
SELECT category, '', 0 FROM inventory
UNION
SELECT category, name, count FROM inventory
WHERE category IN
(SELECT category FROM inventory
UNION
SELECT category FROM inventory)
AND count > 1;
什麼,我得到的是:
category '' 0
---------- ---------- ----------
fruit 0
fruit apple 4
fruit banana 3
fruit peach 2
meat 0
vegetable 0
vegetable carrot 2
vegetable spinach 5
而實際上我想要的這種情況下沒有meat
行。
我認爲問題在於WHERE
子句只適用於SELECT
之後的第一個UNION
。但是我怎麼能把條件放在第一個SELECT
?誰能幫我?提前致謝!
謝謝,它的偉大工程!所以'UNION ALL'之前的部分是獲得項目的最大數量大於1的所有類別行,並且後半部分是獲得所有數量大於1的項目行,然後將結果和整理它們。是對的嗎? – Chromium
是的(你可以試試這些查詢)。 –
是的,我試過了。我只是想知道它是如何工作的 – Chromium