Table 1
表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:
我现在用两个sql和更多的代码做这个:
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?
如果两者都在,我将继续我的脚本的其余部分。我如何在MySql中做这样的事情?
2 个解决方案
#1
5
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
#2
0
This may help you -
这可能对你有所帮助
$query = "SELECT SUM(Case when id=1 then 1 else 0 end) as count_one,
SUM(Case when id=2 then 1 else 0 end) as count_two FROM table";
#1
5
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
#2
0
This may help you -
这可能对你有所帮助
$query = "SELECT SUM(Case when id=1 then 1 else 0 end) as count_one,
SUM(Case when id=2 then 1 else 0 end) as count_two FROM table";