我有三个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以加快速度?
最佳答案
原始查询可能能够利用表上的索引(基于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')
关于mysql - mysql在具有不同where子句的单个表中的多个计数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14583529/