MySQL查询选择

标签 mysql

我有两个表:

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/

相关文章:

MySql如何根据同一行中的主项获取名称?

mysql - 如何将变量设置为触发器 MYSQL 中存储过程的结果?

php - zf2 "join as"语法

mysqldump 恢复备份需要很长时间,有什么问题吗?

mysql - 如何求和组值?

PHP:从函数中获取mysql数据作为对象

php - 添加一个什么都不做的复选框!if empty 坏还是聪明?

php - 为什么这个 MySQL 查询会减慢我的代码

MySQL:如何找出哪些表引用了特定表?

MySQL评级数据库结构