I have the following table "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
and I want all IDs of objects that are never used in the parent column and where memo = local object. So in this example it would be row 4, cause there isn't any row in this table with parent = 4 and its memo = local object.
What would be a good sql statement for that case?
Mine looks like this:
select ID from db.myTable t1 where t1.memo = 'local object' and not exists
(select * from db.myTable t2 where t2.parent = t1.ID)
I usually do a left outer join for these types of statements, combined with a filter, something like this;
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
Not sure if it's more efficient, but it looks nicer (IMHO).
Your query is fine:
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);
For performance, you want indexes on mytable(memo, id)
and mytable(parent)
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.