MySQL:子选择不返回预期的COUNT结果

时间:2016-01-14 20:10:04

标签: mysql count subquery

我有以下查询,它运行并处理正常,问题是子选择只返回1或0,它应该返回过去24小时内所有记录的COUNTWHERE子句中所指定的那样,并且所有这些都属于子选择标准。

我怀疑这些问题仅适用于子选择,而是一次只在ID进行比较,但我尝试将WHERE tbr.ID = ID更改为WHERE tbr.ID IN (ID),但它仍然只返回1或0。

别名总数上的COUNT返回728,因此数据确实存在并且在过去24小时内有效,这已经过验证。

SELECT COUNT(tbr.`ID`) AS `total`
, (SELECT COUNT(`ID`) FROM `cred` WHERE tbr.`ID` = `ID` AND `match` = 'EXACT' AND `number` <> '') AS `exact`
, DATE(NOW()) AS `reportDate`
FROM `cred` tbr
WHERE tbr.`processed` >= (NOW() - INTERVAL 1 DAY);

2 个答案:

答案 0 :(得分:1)

也许条件聚合会有所帮助。

SELECT 
   COUNT(tbr.`ID`) AS `total`
 , COUNT(case when match` = 'EXACT' AND `number` <> '' then tbr.`ID` end) AS `exact`
 , DATE (NOW()) AS `reportDate`
FROM `cred` tbr
WHERE  tbr.`processed` >= (NOW() - INTERVAL 1 DAY);

样本数据和预期结果有助于选择解决方案。

答案 1 :(得分:0)

SELECT COUNT(tbr.`ID`) AS `total`
, (SELECT COUNT(`ID`) 
    FROM `cred` 
    WHERE `ID` IN (tbr.`ID`)    --try with inverting this condition
        AND `match` = 'EXACT' 
        AND `number` <> '') AS `exact`
, DATE(NOW()) AS `reportDate`
FROM 
    `cred` tbr
WHERE 
    tbr.`processed` >= (NOW() - INTERVAL 1 DAY);