2

我有这张桌子...

--------------------------------------
| user_id |  status   |  status_date |
--------------------------------------
|    1    |  Current  |  2012-08-01  |
|    1    |  Referral |  2012-03-14  |
|    2    |  Referral |  2012-04-23  |
|         |           |              |
--------------------------------------

我将如何查询以找到一个不同的 user_id,其推荐日期在 2012 年 6 月 30 日之前并且当前日期在 2012 年 6 月 30 日之后或根本没有当前状态记录?

数据库是 MySQL。

4

3 回答 3

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 BYwithHAVINGCOUNT(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
    )

这将取决于您的索引和数据量,哪个表现更好,我想在大多数情况下它将是前者

于 2012-10-30T16:58:01.233 回答
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')
于 2012-10-30T16:53:18.100 回答
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'));
于 2012-10-30T16:53:29.637 回答