Mysql:使用单个查询获取条件和无条件数据

时间:2014-04-28 09:56:29

标签: mysql

我需要使用和不使用条件语句来获取一些数据的计数。现在我正在做的是我写了两个不同的查询,即

$sql = "select COUNT(`id`) as totalcount from `table1`";
$result1 = mysql_query($sql) or die(mysql_error());
$totalRes = mysql_fetch_assoc($result1);

$sql = "select COUNT(`id`) as count1 from `table1` where `field_name` = 'someting' ";
$result2 = mysql_query($sql) or die(mysql_error());
$condRes = mysql_fetch_assoc($result2);

我可以在一个查询中写下这两个吗?

2 个答案:

答案 0 :(得分:1)

一种方法

SELECT 
COUNT(`id`) as totalcount,
sum(field_name='someting') as count1
FROM `table1`;

DEMO

答案 1 :(得分:0)

试试这个,

select COUNT(`id`) as totalcount, SUM(field_name='something') as conditional_total
from `table1`