[英]How to query a SQL statement which depends on other values of same table?
I have a table with 3 columns( name, objectroot_dn, distinguishedname). 我有一个包含3列的表(名称,objectroot_dn,专有名称)。 Here distinguishedname is like a parent to objectroot_dn .
在这里, 专有名称就像objectroot_dn的父代 。 I have to find whether for each objectroot_dn is there a child exists or not?
我必须查找每个objectroot_dn是否存在一个孩子?
I can do this using the query below. 我可以使用下面的查询来做到这一点。 It will return True if there is a child, False if there is not.
如果有孩子,它将返回True,否则将返回False 。 But my problem is when the total dataset gets increased it takes lots of time.
但是我的问题是,当总数据集增加时,会花费很多时间。
For example, If the total number of row is 50,000 then it takes 10 mins for this query to complete. 例如,如果总行数为50,000,则此查询需要10分钟才能完成。
Since I'm using a framework for different database, I can't index the columns. 由于我为不同的数据库使用框架,因此无法为列建立索引。
SELECT name, objectroot_dn, distinguishedname, CASE WHEN (SELECT count(*) FROM (SELECT name FROM elaoucontainergeneraldetails WHERE objectroot_dn = dn.distinguishedname LIMIT 1) AS tabel1) > 0 THEN 'True' ELSE 'False' END FROM elaoucontainergeneraldetails AS dn WHERE objectroot_dn = 'SOME_VALUE';
Please let me know how can I increase the speed of this query. 请让我知道如何提高查询速度。
Thanks in advance. 提前致谢。 Appreciate all help.
感谢所有帮助。
You can have the same solution using left join or exists: 您可以使用左连接或存在相同的解决方案:
SELECT
dn.name,
dn.objectroot_dn,
dn.distinguishedname,
CASE
WHEN dn_in.objectroot_dn is not null
THEN 'True'
ELSE 'False'
END
FROM elaoucontainergeneraldetails AS dn
LEFT JOIN elaoucontainergeneraldetails dn_in on dn_in.objectroot_dn = dn.distinguishedname
WHERE objectroot_dn = 'SOME_VALUE';
EXISTS(subquery)
yields a boolean value: EXISTS(subquery)
产生一个布尔值:
SELECT dn.name
, dn.objectroot_dn
, dn.distinguishedname
, EXISTS (SELECT *
FROM elaoucontainergeneraldetails nx
WHERE nx.objectroot_dn = dn.distinguishedname
) AS truth_value
FROM elaoucontainergeneraldetails AS dn
WHERE dn.objectroot_dn = 'SOME_VALUE'
;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.