我有这张桌子......
--------------------------------------
| user_id | status | status_date |
--------------------------------------
| 1 | Current | 2012-08-01 |
| 1 | Referral | 2012-03-14 |
| 2 | Referral | 2012-04-23 |
| | | |
--------------------------------------
如何查询在2012-06-30之前找到推荐日期且2012-06-30之后的当前日期或根本没有当前状态记录的不同user_id?
数据库是MySQL。
答案 0 :(得分:2)
您可以使用LEFT JOIN执行此操作:
SELECT DISTINCT T.User_ID
FROM T
LEFT JOIN T T2
ON t.User_ID = T2.User_ID
AND t2.Status = 'Current'
WHERE T.Status_Date < '20120630'
AND T.Status = 'Referral'
AND (t2.Status_Date > '20120630' OR t2.Status_date IS NULL)
或者,GROUP BY
与HAVING
和COUNT(CASE ...)
SELECT t.User_ID
FROM T
GROUP BY t.user_ID
HAVING COUNT(CASE WHEN t.Status = 'Referral' AND t.Status_Date < '20120630' THEN 1 END) > 0
AND ( COUNT(CASE WHEN t.Status = 'Current' AND t.Status_Date > '20120630' THEN 1 END) > 0
OR COUNT(CASE WHEN t.Status = 'Current' THEN 1 ELSE 0 END) = 0
)
这将取决于您的索引和数据量,哪些表现更好,我想在大多数情况下它将是前者
答案 1 :(得分:1)
这应该这样做:
SELECT DISTINCT user_id
FROM YourTable T
WHERE status = 'Referral'
AND status_date < '2012-06-30'
AND NOT EXISTS (SELECT user_id FROM YourTable
WHERE user_id = T.user_id AND status = 'Current'
AND status_date < '2012-06-30')
答案 2 :(得分:0)
避免使用MySQL进行内部选择。 5.5及以下版本的所有版本都无法正确优化。使用JOIN:
SELECT distinct t1.user_id
FROM tablename t1
LEFT JOIN tablename t2 on t1.user_id = t2.user_id AND t1.status != t2.status
WHERE t1.status = 'Referral'
AND t1.status_date '2012-06-30'
AND ( (t2.status IS NULL) OR
(t2.status = 'Current' AND t2.status_date > '2012-06-30'));