如何将这两个查询合并为一个?

时间:2011-02-15 23:26:23

标签: php mysql merge

$a = mysql_query("SELECT COUNT(*) as `count_1` FROM `table_1` WHERE `this_1` = '1'");
$b = mysql_fetch_assoc($a);

$c = mysql_query("SELECT COUNT(*) as `count_2` FROM `table_1` WHERE `this_2` = '1'");
$d = mysql_fetch_assoc($c);

2 个答案:

答案 0 :(得分:3)

使用UNION ALL将其设为一个查询:

SELECT COUNT(*) as count_1 FROM table_1 WHERE this_1 = '1'
UNION ALL
SELECT COUNT(*) as count_2 FROM table_1 WHERE this_2 = '1'

这样会导致

$a = mysql_query("...the complete query from above...");

答案 1 :(得分:2)

您可以使用COUNT()内的条件来计算出现次数。这样,您将获得包含多列的单行:

SELECT COUNT(this_1 = '1' OR NULL) AS count_1, COUNT(this_2 = '1' OR NULL) AS count_2