mysql 聚合查询返回错误结果

mysql aggregate query returning wrong result

我有两个 table 中的数据需要加入,return table 之一中记录的出现次数,

Employee table 中的数据看起来像,

empId  workpatternId
    1        20

workPattern tables中的数据看起来像,

workpatternId  monday tuesday wednesday thursday friday saturday sunday
   20           ALL     ALL     ALL       ALL     NULL   NULL     ALL 

下面的查询应该是 return 5,这是 ALL 的计数,但是 returns 7 相反,

SELECT empId,b.workingPatternId, COUNT(monday='ALL') +
 COUNT(tuesday='ALL') + COUNT(wednesday='ALL')+ COUNT(thursday='ALL') + 
    COUNT(friday='ALL')+ COUNT(saturday='ALL')+ COUNT(sunday='ALL') AS COUNT
      FROM workPattern b 
 join Employee e on (e.workpatternId = b.workpatternId) and e.empId = 1
         GROUP BY empId ;

查询有什么问题?

编辑

dbfiddle

我看不出聚合的意义,因为似乎每个 empIdworkPattern 中只有一行。你可以这样写:

SELECT e.empId, wp.workingPatternId, 
      (wp.monday    = 'ALL') 
    + (wp.tuesday   = 'ALL') 
    + (wp.wednesday = 'ALL') 
    + (wp.thursday  = 'ALL') 
    + (wp.friday    = 'ALL') 
    + (wp.saturday  = 'ALL') 
    + (wp.sunday    = 'ALL') cnt
FROM workPattern wp
INNER Employee e on e.workpatternId = wp.workpatternId 
WHERE e.empId = 1

如果出于某种原因需要聚合,那么您需要 sum() 而不是 count():后者计算所有 non-null 值,而 false 条件被评估为 0(不是 null,因此在您的查询中考虑了它):

SELECT 
    SUM(
          (wp.monday    = 'ALL') 
        + (wp.tuesday   = 'ALL') 
        + (wp.wednesday = 'ALL') 
        + (wp.thursday  = 'ALL') 
        + (wp.friday    = 'ALL') 
        + (wp.saturday  = 'ALL') 
        + (wp.sunday    = 'ALL')
    ) cnt
FROM workPattern wp
INNER JOIN Employee e on e.workpatternId = wp.workpatternId 
WHERE e.empId = 1

这有效:

 SELECT empId,b.workingPatternId, sum(Monday='ALL') + sum(Tuesday='ALL') + sum(Wednesday='ALL')+ sum(Thursday='ALL') + sum(Friday='ALL') + sum(Saturday='ALL')+ sum(Sunday='ALL') AS COUNT
 FROM WorkPatterns b 
 JOIN Employee e 
        ON (e.workingPatternId = b.workingPatternId) 
        AND e.empId = 1   
 GROUP BY empId ;