MySQL Sub选择多个条件

时间:2013-10-28 17:31:03

标签: mysql sql join subquery

我正在尝试将多个select语句组合成一个查询但似乎无法正确使用它。我想我需要做一个子选择。我敢肯定,这是一件很简单的事情。在第二次查询之后我有更多但是除了不同的TAS_UID号之外它们都是相同的设置。

查询1:

SELECT USR_USERNAME AS 'User Name', 
           COUNT(AD.app_uid) AS 'Total'
FROM   APP_DELEGATION AD
JOIN   USERS U
WHERE  AD.USR_UID = U.USR_UID
AND    AD.DEL_THREAD_STATUS = 'Closed'
GROUP BY AD.USR_UID

查询2:

SELECT USR_USERNAME AS 'User Name', 
       COUNT(AD.app_uid) AS 'Total for Task A'
FROM   APP_DELEGATION AD
JOIN   USERS U
WHERE  AD.USR_UID = U.USR_UID
AND    AD.DEL_THREAD_STATUS = 'Closed'
AND    AD.TAS_UID = '23423423455'
GROUP BY AD.USR_UID

2 个答案:

答案 0 :(得分:2)

您的查询不正确。它们应该类似于以下内容:

查询1:

SELECT USR_USERNAME AS 'User Name', COUNT(AD.app_uid) AS 'Total'
FROM APP_DELEGATION AS AD
  JOIN USERS AS U 
  ON AD.USR_UID = U.USR_UID
WHERE AD.DEL_THREAD_STATUS = 'Closed'
GROUP BY AD.USR_UID

查询2:

SELECT USR_USERNAME AS 'User Name', COUNT(AD.app_uid) AS 'Total for Task A'
FROM APP_DELEGATION AS AD
  JOIN USERS AS U 
  ON AD.USR_UID = U.USR_UID
WHERE AD.DEL_THREAD_STATUS = 'Closed'
  AND AD.TAS_UID = '23423423455'
GROUP BY AD.USR_UID

答案 1 :(得分:1)

您可以使用Case语句执行此操作。像这样:

SELECT USR_USERNAME AS 'User Name'
  ,COUNT(AD.app_uid) AS 'Total'
  ,SUM(case when AD.TAS_UID = '23423423455' then 1 else 0 end) as 'Total for Task A'
FROM APP_DELEGATION AS AD
  JOIN USERS AS U 
  ON AD.USR_UID = U.USR_UID
WHERE AD.DEL_THREAD_STATUS = 'Closed'
GROUP BY AD.USR_USERNAME