询问MySQL中的查询

时间:2013-02-19 09:30:29

标签: mysql sql select

我有这样的表:

CreateDate  |  UserID
2012-01-1   |     1
2012-01-10  |     2
2012-01-20  |     3
2012-02-2   |     4
2012-02-11  |     1
2012-02-22  |     2
2012-03-5   |     3
2012-03-13  |     4
2012-03-17  |     5

我需要查询来显示2013年2月1日之后创建的用户ID,并且在2013年2月1日之前不存在于数据库中

从上面的例子中,结果必须是:

CreateDate  |  UserID
2012-02-2   |     4
2012-03-13  |     4
2012-03-17  |     5

只能在没有存储过程的单个查询中解决吗?

2 个答案:

答案 0 :(得分:1)

您可以使用一个子查询,该子查询单独获取UserID之前存在的Feb. 2, 2013,然后使用LEFT JOIN将子查询的结果连接回表本身。

SELECT  a.*
FROM    tableName a
        LEFT JOIN 
        (
            SELECT  UserID
            FROM    tableName
            WHERE   CreateDate < '2013-02-01'
        ) b ON a.userID = b.userID
WHERE   a.CreateDate > '2013-02-01' AND
        b.userID IS NULL

要获得更快的效果,请在列INDEX上添加userID

答案 1 :(得分:0)

这是一种方法:

select 
  CreateDate,
  UserID
from Users
where CreateDate >= '2012-02-01'
and UserId not in (
  select UserId
  from Users
  where CreateDate < '2012-02-01'
)

SqlFiddle链接:http://www.sqlfiddle.com/#!2/7efae/2