[英]SQL check if row value in one column is in another column that is a list of strings
[英]How to check if value of one column is in another column of another row
我有下表“myTable”:
ID | Name | Parent | Memo
________________________________________
1 | Obj1 | 1 | server object
2 | Obj2 | 1 | local object
3 | Obj3 | 2 | server object
4 | Obj4 | 3 | local object
我想要父列中从未使用过的对象的所有 ID,其中 memo = 本地对象。 所以在这个例子中,它是第 4 行,因为这个表中没有任何一行父 = 4 并且它的备忘录 = 本地对象。
对于这种情况,什么是好的 sql 语句?
我的看起来像这样:
select ID from db.myTable t1 where t1.memo = 'local object' and not exists
(select * from db.myTable t2 where t2.parent = t1.ID)
我通常为这些类型的语句做一个左外连接,结合一个过滤器,像这样;
select ID
from db.myTable t1
left join db.myTable t2
on t2.parent = t1.ID
where t1.memo = 'local object'
and t2.parent is null -- arbitrary none nullable column
不确定它是否更有效,但它看起来更好(恕我直言)。
您的查询很好:
select ID
from db.myTable t1
where t1.memo = 'local object' and
not exists (select 1 from db.myTable t2 where t2.parent = t1.ID);
为了提高性能,您需要mytable(memo, id)
和mytable(parent)
上的索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.