MySQL查询选择

时间:2012-01-10 18:50:16

标签: mysql

我有两张桌子:

t1
____________
projectID
userID
projectExpiration

t2
____________
usrID
subscriptioID
subscriptionExpiration

我需要从T1中选择满足以下条件的项目ID:

t1.projectExpiration = older then 3 months
t2.subscriptioID = '5'
t2.expiration = older then 3 months

用户可能在t2中有其他订阅。我只需要一个具有ID为“5”

的订阅条目的结果

我需要帮助把它们放在一起。

这是我到目前为止所得到的:

SELECT projectID
FROM t1
LEFT JOIN t2 ON (t1.userID = t2.userID)
WHERE t1.projectExpiration < (CURDATE() - INTERVAL 3 MONTH)
  AND t2.subscriptionExpiration = 5
      AND t2.subscriptionExpiration < (CURDATE() - INTERVAL 3 MONTH)

感觉我被卡住了......

2 个答案:

答案 0 :(得分:1)

您希望not exists检查以确保5是唯一的一行:

select
    *
from
    t1 x
    inner join t2 y on
        x.userid = y.userid
where
    x.projectexpiration < curdate() - interval 3 month
    and y.subscriptionid = 5
    and not exists (
        select
            1
        from
            t2 z
        where
            z.userid = x.userid
            and z.subscriptionid <> 5
    )

我还应该提一下,我在这里使用inner join代替left join。这是因为您不希望获取t2行不存在的行(您在nulls子句中没有考虑where)。所以,这只是不必要的开销。 inner join让我们以更清晰的方式获得您想要的结果集。

答案 1 :(得分:1)

SELECT
    sq1.projectID
FROM
    (SELECT * FROM T2 WHERE subscriptioID=5
    AND subscriptionExpiration < DATE(now() - INTERVAL 3 MONTH)) sq2
    INNER JOIN
    (SELECT * FROM T1 WHERE projectExpiration < DATE(now() - INTERVAL 3 MONTH)) sq1
    ON sq12.usrID=sq1=userID
;

SELECT
    sq1.projectID
FROM
    (SELECT usrID userID,subscriptioID,subscriptionExpiration
    FROM T2 WHERE subscriptioID=5
    AND subscriptionExpiration < DATE(now() - INTERVAL 3 MONTH)) sq2
    INNER JOIN
    (SELECT * FROM T1 WHERE projectExpiration < DATE(now() - INTERVAL 3 MONTH)) sq1
    USING (userID)
;

SELECT
    sq1.projectID
FROM
    (SELECT * FROM T2 WHERE subscriptioID=5
    AND subscriptionExpiration < DATE(now() - INTERVAL 3 MONTH)) sq2
    INNER JOIN
    (SELECT projectID,userID usrID,projectExpiration         
    FROM T1 WHERE projectExpiration < DATE(now() - INTERVAL 3 MONTH)) sq1
    USING (usrID)
;