如何从同一个表中简化计数查询

时间:2016-11-01 13:47:08

标签: php mysql

您好我正在尝试减少代码如何简化这些行。如果问题未达到标准,请建议编辑。

$invCount = $conn->query("SELECT 
(SELECT COUNT(*) FROM r_job_invitations WHERE id_job='".$_POST['JobId']."' and inv_st=1) as clginvcount,
(SELECT COUNT(*) FROM r_job_invitations WHERE id_job='".$_POST['JobId']."' and inv_res=1) as clgaccptdcount,
(SELECT COUNT(*) FROM r_job_invitations WHERE id_job='".$_POST['JobId']."' and inv_res=2) as clgrejectedcount,
(SELECT COUNT(*) FROM r_job_invitations WHERE id_job='".$_POST['JobId']."' and inv_res=0) as clgnoresponsecount");
$invCountRes = $invCount->fetch_assoc();

1 个答案:

答案 0 :(得分:1)

如果您在coumn inv_res中只有值0,1,2,则可以使用此查询,还请首先验证您的用户输入:

$jobId = mysqli_real_escape_string($_POST['JobId']);
SELECT 
    count(*), inv_res 
FROM  r_job_invitations 
WHERE 
    id_job ='".$jobId."' 
GROUP BY inv_res

如果您有更多值,请使用以下

SELECT 
    count(*), inv_res 
FROM  r_job_invitations 
WHERE 
    id_job ='".$jobId."' AND 
    inv_res IN(0,1,2)
GROUP BY inv_res