如何从子查询中获取UNIQUE数?

时间:2013-05-27 22:05:09

标签: php mysql

以下是查询:

    SELECT count(a.id) as itemCount, 
           concat(a.firstname, ' ', a.lastname) as name, 
           oi.status, a.id as adminID, 
           (SELECT count(a.id) as oldItemsCount 
                   FROM bl_orderitems oi, 
                        bl_researcher r,             
                        tbladmins a 
                   WHERE oi.status='Pending' AND 
                         r.id=oi.researcherid AND 
                         r.researchermanagerid=a.id AND
                         DATE(oi.regdate)=DATE_SUB(CURDATE(), INTERVAL 3 DAY))
                   as oldItemCount
    FROM bl_orderitems oi, 
           bl_researcher r,
           tbladmins a 
    WHERE oi.status in ('Pending', 'QA') AND
           r.id=oi.researcherid AND 
           r.researchermanagerid=a.id 
    GROUP BY 
          name, adminID, oi.status;

此查询应返回如下内容:

 itemCount    name            status    adminID  oldItemCount 
    5         John McKay      Pending      20        125
    15        Clown Ho        QA           12        125
    39        Jack Fell       Pending      13        125
    5         Mark Grunigen   Pending       2        125
    1         Kim Jun Li      QA            2        125
    206       Abama Oladen    Pending       4        125

当我试图实现它时,它返回UNIQUE oldItemCount。

oldItemCount应为count(a.id)套件“DATE(oi.regdate)=DATE_SUB(CURDATE(), INTERVAL 3 DAY))

如果我在子查询上尝试使用DISTINCT,它会显示Operand should contain 1 column(s)

1 个答案:

答案 0 :(得分:3)

您要找的是COUNT(DISTINCT)

编辑:根据你的评论,你应该尝试这样的事情:

SELECT count(DISTINCT oi.id) as itemCount, 
       concat(a.firstname, ' ', a.lastname) as name, 
       oi.status, a.id as adminID, 
       (SELECT count(oi2.id) as oldItemsCount 
               FROM bl_orderitems oi2, 
                    bl_researcher r2
               WHERE oi2.status='Pending' AND 
                     r2.id=oi.researcherid AND 
                     r2.researchermanagerid=a.id AND
                     DATE(oi2.regdate)=DATE_SUB(CURDATE(), INTERVAL 3 DAY))
               as oldItemCount
FROM bl_orderitems oi, 
       bl_researcher r,
       tbladmins a 
WHERE oi.status in ('Pending', 'QA') AND
       r.id=oi.researcherid AND 
       r.researchermanagerid=a.id 
GROUP BY 
      name, adminID, oi.status;

它更简单,可能符合您的需求。