user317005
user317005

Reputation:

How can I merge these two queries into one?

$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);

Upvotes: 2

Views: 119

Answers (2)

CodeTwice
CodeTwice

Reputation: 2936

You can use a condition inside the COUNT() to count the occurences. This way you will get a single row with multiple columns:

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

Upvotes: 2

user330315
user330315

Reputation:

Use a UNION ALL to make it a single query:

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'

So that would result in

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

Upvotes: 3

Related Questions