Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySql Doing two counts with two different wheres from the same table

Tags:

sql

mysql

Table 1

"id"    "name"      "description"   "path"                              "country"   "status"
"1"     "Title 1"   "Description 1" "US > Consumer > Home Applicances"  "US"        "0"
"2"     "Title 2"   "Description 2" "US > Business > Legal Charges"     "UK"        "0"

I'm trying to do two counts with different wheres from the same table.

I came across other questions here, but none like the way I'm doing it.

I'm currently doing it with two sqls and a lot more code:

select count(id) from table where id = 1 and select count(id) from table where id = 2

If both were there, I'll go on with the rest of my script. How can I do something like this in MySql?

like image 605
jmenezes Avatar asked Dec 14 '25 05:12

jmenezes


1 Answers

You can use subselects.

SELECT * FROM 
  (SELECT COUNT(id) AS count_one FROM table WHERE id = 1) a,
  (SELECT COUNT(id) AS count_two FROM table WHERE id = 2) b
like image 156
Angelo Fuchs Avatar answered Dec 16 '25 06:12

Angelo Fuchs