1

我有三个执行 COUNT 的 SELECT 语句。认为结合这些在mysql上会更有效和更友好:

$query = $db->query("SELECT count(category) FROM table WHERE cid='290463' and category = 'x'"); 
         $tot_x = $db->result($query, 0);

$query = $db->query("SELECT count(category) FROM table WHERE cid='290463' and category = 'y'"); 
         $tot_y = $db->result($query, 0);

$query = $db->query("SELECT count(category) FROM table WHERE cid='290463' and category = 'z'"); 
         $tot_z = $db->result($query, 0);

一句话:

SELECT 
    SUM(category='x' AND cid='290463') as tot_x, 
    SUM(category='y' AND cid='290463') as tot_y, 
    SUM(category='z' AND cid='290463') as tot_z 
FROM table

问题是,新语句比单独运行原来的三个语句要慢。

任何人都能够阐明为什么新语句较慢以及改进 SELECT 以使其更快的建议?

4

2 回答 2

3

您的原始查询可能能够利用表上的索引(基于您的 where 子句),确保只读取表上相对较小比例的记录 - 而不是整个表,如统一查询。尝试将等效条件添加回 where 子句,如下所示:

SELECT 
    SUM(category='x') as tot_x, 
    SUM(category='y') as tot_y, 
    SUM(category='z') as tot_z 
FROM table
WHERE cid='290463' and category in ('x', 'y', 'z')
于 2013-01-29T13:04:29.080 回答
0
SELECT 
    SUM(IF(category='x',1,0))as tot_x, 
    SUM(IF(category='y',1,0))as tot_y, 
    SUM(IF(category='z',1,0))as tot_z
FROM table
WHERE cid='290463'
GROUP BY category
于 2013-01-29T13:03:43.593 回答