我有這個表:優化MySQL查詢與布爾值
CREATE TABLE IF NOT EXISTS `products` (
`product_id` int(11) NOT NULL AUTO_INCREMENT,
`supplier_id` int(11) NOT NULL,
`allowed` varchar(256) NOT NULL,
`blocked` varchar(256) NOT NULL,
`approved` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`product_id`),
KEY `supplier_id` (`supplier_id`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
「批准」是一個布爾0/1場
「封鎖」和「允許」持有國家代碼,如「美國CA FR」
我運行此查詢:
SELECT DISTINCT supplier_id
FROM products
WHERE (
supplier_id=0 OR
supplier_id = 1207077 OR
supplier_id = 1207087 OR
supplier_id = 1207079 OR
supplier_id = 1207082 OR
supplier_id = 1207083 OR
supplier_id = 1207086 OR
supplier_id = 1207084 OR
supplier_id = 1207078 OR
supplier_id = 1207085 OR
supplier_id = 1207094 OR
supplier_id = 1207097 OR
supplier_id = 1207095 OR
supplier_id = 1207089 OR
supplier_id = 1207091
) AND (
(`blocked` NOT LIKE '%US%' AND `allowed` ='') OR
`allowed` LIKE '%US%'
) AND approved=1;
它運行在約0.02秒。有關如何優化它的任何建議?謝謝。
在supplier_id上添加索引,批准,阻止和允許。讓批准進來AND條款 – Steve 2014-10-29 23:48:59
第一你也可以擺脫所有這些ORs並使用supplier_id IN(0,1207077,1207087,...) – Brian 2014-10-29 23:50:22
@Brian它將在背景中是同樣的事情... won不改善表現。 – Steve 2014-10-30 00:45:29