MySql Sub Select

时间:2014-11-25 22:38:46

标签: mysql

我需要查询一个表并收集有和没有列值的计数。

包含'src'列值的记录数和没有。

的计数

问题

结果仅包含一天,而不是每行每天。每行都有相同的值。

预期结果

DAY,包含价值,不包含价值

查询

SELECT 
    DATE_FORMAT(edate,'%Y-%m-%d') as day,

(SELECT 
COUNT(id) FROM  entries WHERE src='a string' and color = 'red') with_value,

(SELECT 
COUNT(id) FROM  entries WHERE src='' and color = 'red') without_value

FROM entries 

GROUP BY day
ORDER BY day DESC

3 个答案:

答案 0 :(得分:1)

您可以使用此技术在没有子查询的情况下执行此操作:

SELECT 
    DATE_FORMAT(edate,'%Y-%m-%d') as day,
    SUM(src = 'a string') as with_value,
    SUM(src = '') as without_value

FROM entries 

GROUP BY day
ORDER BY day DESC

我在那里做的是利用了MySQL does not have a Boolean data type,而TRUE1FALSE0相同的事实,实际上SUM充当满足条件的COUNT行。

答案 1 :(得分:1)

我会使用条件聚合来做到这一点:

SELECT DATE_FORMAT(edate, '%Y-%m-%d') as day,
       SUM(src = 'a string' and color = 'red') as with_value,
       SUM(src = '' and color = 'red') as without_value
FROM entries 
GROUP BY day
ORDER BY day DESC;

在MySQL中,布尔表达式在整数上下文中被视为0(对于false)和(1表示为true)。这使它们便于聚合。

答案 2 :(得分:0)

如果您想要每天聚合结果,那么您需要在计算聚合的查询(-ies)中按天执行分组。您正在对父查询进行分组。

无论如何,你不需要这个子查询,最好避免使用它们:

SELECT
    DATE_FORMAT(edate,'%Y-%m-%d') as day,
    SUM(CASE WHEN src='a string' THEN 1 ELSE 0 END CASE)
      AS with_value
    SUM(CASE WHEN src='' THEN 1 ELSE 0 END CASE)
      AS without_value
FROM entries
WHERE color = 'red'
GROUP BY day
ORDER BY day DESC