我有两个表:
t1
____________
projectID
userID
projectExpiration
t2
____________
usrID
subscriptioID
subscriptionExpiration
我需要从满足以下条件的T1中选择porject 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)
感觉自己被卡住了...
最佳答案
你想要一个 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
让我们以更清晰的方式找到您想要的结果集。
关于MySQL查询选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8808788/