如何在 Mysq 中查询排除条件行



我在下面提到了表格:

表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'))

据我了解,您想要唯一唯一的cat_id:

Select ID,cat_id,Date,key
From Table1
Where key IN (Select key from table2 where value <> 'Closed')
AND cat_id in (Select cat_id from 
(select cat_id,count(*) 
from table1 
group by cat_id 
having count(*)=1
) 
)

尝试反转选择:

SELECT ID, cat_id, Date, key FROM Table1 t1
LEFT JOIN Table2 t2 ON t1.key=t2.key
WHERE t1.cat_id NOT IN
(SELECT cat_id FROM Table1 b1
LEFT JOIN Table2 b2 ON b1.key=b2.key
WHERE b2.Value='Closed');

这将排除带有UTV-12的两行,因为其中一行被标记为关闭:

请检查以下查询:

SELECT t1.ID, t1.cat_id, t1.Date, t1.key FROM
Table1 t1 
LEFT JOIN Table2 t2 ON t1.key=t2.key
WHERE t1.Date>='2018-03-01 00:00:00'
AND t1.cat_id IN (select b1.cat_id FROM Table1 b1
LEFT JOIN Table2 b2 ON b1.key=b2.key WHERE b2.Value!='Closed')

最新更新