我想通过单个查询获得总ROW类型。让我解释一下。
通常我使用此查询来获取其中一个:
$database->query("SELECT COUNT(*) as c FROM workers WHERE job = 1");
$totalWorkers = $database->fetchObject()->c;
所以,它完美无缺,但还有7种工作类型(0-8)。这只是(1)。
我可以这样做:[太多要求执行,不好]
$database->query("SELECT COUNT(*) as c FROM workers WHERE job = 1");
$totalWorkers1 = $database->fetchObject()->c;
$database->query("SELECT COUNT(*) as c FROM workers WHERE job = 2");
$totalWorkers2 = $database->fetchObject()->c;
但是我不想执行这些多个查询,有没有简单的方法呢?我想得到那样的计数结果:
$totalWorkers2 = $database->fetchObject()->type_1;
$totalWorkers2 = $database->fetchObject()->type_2;
我到处搜索过但我找不到&想想任何逻辑...
答案 0 :(得分:1)
item1[0];
或
SELECT sum(IF(job=1,1,0)) as job1count, sum(IF(job=2,1,0)) as job2count FROM workers;
取决于您是否希望它们在同一记录中
答案 1 :(得分:0)
您可以按作业分组结果
$database->query("SELECT job, COUNT(*) as c FROM workers WHERE job in (1,2) group by job");
$tmp = $database->fetchAll();
$result = array();
foreach ($tmp as $o) $result[$o->job] = $o->c;
然后使用数组$result
作为$result[1]
作业= 1,$result[2]
作业= 2
如果您需要所有作业的计数
,您可以按作业WHERE job in (1,2)
删除过滤器