mysql - Mysql中如何查询排除条件行

标签 mysql

我有下面提到的表格:

表1

ID     cat_id   Date                   key
IY-1   UTV-12   2018-03-18 15:04:25    xxt-14-yt
IY-2   UTV-12   2018-01-01 18:25:19    xxt-15-yt
IY-3   UTV-14   2018-03-05 13:12:14    xxt-17-yt
IY-4   UTV-15   2018-04-03 17:26:11    xxt-14-yt

表2

Key         Value
xxt-14-yt   Pending
xxt-15-yt   Closed
xxt-17-yt   Open

在上表中,cat_id 是为特定类别用户分配的唯一 ID,key 映射到状态。

我只想获取 cat_id 状态不等于 Closed 状态的行。

所需输出:

ID     cat_id   Date                   key
IY-3   UTV-14   2018-01-05 13:12:14    xxt-17-yt
IY-4   UTV-15   2018-07-03 17:26:11    xxt-14-yt

我正在使用下面提到的查询,但它无法正常工作。

查询:

select ID, cat_id, Date, key from Table1 t1
left join Table2 t2 on t1.key=t2.key
where t1.cat_id IN
(select cat_id from Table1 b1
left join Table2 b2 on b1.key=b2.key
where b2.Value!='Closed') and DATE(t1.Date)>='2018-03-01';

最佳答案

我还没有测试过,但我认为它应该有效:

select * from table1 a 
left join 
    (select cat_id from table1 a 
        join table2 b on a.key = b.Key 
        where b.Value = 'Closed') 
    b on a.cat_id = a.cat_id
where b.cat_id is null  

更简单的方法是:

 select * from table1
 where cat_id not in
    (select cat_id from table1 where key in
        (select key from table2 where Value = 'Closed'))

关于mysql - Mysql中如何查询排除条件行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52154172/

相关文章:

mysql - 从 SQL 获取日期

mysql - 无法在 Windows 命令提示符中使用 while 命令

mysql - SQL 结果长度且搜索时不显示任何内容

mysql - 在为 Model Rails 创建对象之前获取下一个对象 ID

php - 不要在循环中重复值

java - 在 php/java/mysql 中不能有正确的 UTF-8 字符集

mysql - SQL联结查询

mysql - 如何在ruby中获取表名数组

mysql - 删除经典 ASP/VBScript 中的四字节 UTF-8 字符(MySQL 相关)

mysql - 如何将带有列表的 JSON 数据转换为使用动态列的 MariaDB SQL Insert 语句