嗨,大家好,stackoverflow社區!我一直在訪問該網站多年,這纔是我的第一篇文章加快SQLite查詢,我可以做到沒有工會?
可以說我有三個表的數據庫:
- 組(組ID,GroupType,MAX1,大小)
- 糖果( candyID,姓名,選擇的)
- 成員(組ID,填充NameID)
例:將糖果工廠。
在糖果工廠中,10種糖果袋由80種不同的糖果製成。
所以:有10種獨特的團體類型(袋),有3種不同的尺寸:(4,5,6);一個組合是由80種獨特的糖果組合而成的。
在此之外,我製作了一個數據庫(有關糖果組合進入組的一些規則)。
在這一點上,我有一個數據庫與40791獨特的糖果袋。
現在我想比較一下糖果的一個集合與數據庫中的所有糖果袋,結果我想要比較集合中缺少3個或更少糖果的數據庫。
-- restore candy status
update candies set selected = 0, blacklisted = 0;
-- set status for candies to be selected
update candies set selected = 1 where name in ('candy01','candy02','candy03','candy04');
select groupId, GroupType, max, count(*) as remainingNum, group_concat(name,', ') as remaining
from groups natural join members natural join candies
where not selected
group by groupid having count(*) <= 3
UNION -- Union with groups which dont have any remaining candies and have a 100% match
select groupid, GroupType, max, 0 as remainingNum, "" as remaining
from groups natural join members natural join candies
where selected
group by groupid having count(*) =groups.size;
上述查詢執行此操作。但我試圖完成的事情是在沒有工會的情況下做到這一點,因爲速度是至關重要的。而且我也是sql新手,非常想學習/看看新的方法。
問候,魯特格爾
請勿更新數據庫以進行選擇。它根本無法擴展(兩個用戶如何同時進行選擇?),它會降低性能,因爲寫入比讀取要慢。還要注意,UNION或尤其是UNION ALL通常速度非常快,通常會擊敗更復雜的單個查詢。 – GolezTrol 2012-03-25 08:47:21
你的示例模式有些問題,因爲沒有什麼可以將'groups'或'members'連接到'candies',所以它將進行交叉連接,除非'members.memberID'應該是'members.candyID' – Seph 2012-03-25 09:00:56