我有以下提到的表格:
表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';
答案 0 :(得分:0)
我还没有测试过,但是我认为它应该可以工作:
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'))
答案 1 :(得分:0)
据我了解,您只需要唯一的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
)
)
答案 2 :(得分:0)
尝试反转选择:
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的两行,因为这些行中有一次被标记为已关闭:
答案 3 :(得分:0)
请检查以下查询:
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')