改进查询有两个where in in子句

时间:2014-03-27 15:50:19

标签: sql

是否有更好的(更有效的)方式来进行此查询?

我不想在同一个查询(SELECT PDATA1 ...)

中搜索两次
SELECT package_ID
FROM t_package
WHERE parent_ID IN (SELECT PDATA1
                    FROM t_object
                    WHERE stereotype = 'Process' AND object_type = 'Package')
OR package_ID IN (SELECT PDATA1
                  FROM t_object
                  WHERE stereotype = 'Process' AND object_type = 'Package')

5 个答案:

答案 0 :(得分:1)

我相信这可以在没有子查询的情况下完成。

SELECT
    DISTINCT(tp.package_ID)
FROM 
    t_package tp
INNER JOIN
    t_object tobj ON tobj.PDATA1 = tp.parent_ID OR tobj.PDATA1 = tp.package_ID
WHERE
    tobj.stereotype = 'Process' AND tobj.object_type = 'Package'

答案 1 :(得分:0)

使用EXISTS,像这样 -

SELECT package_ID
FROM t_package t
WHERE exists(SELECT *                        
FROM t_object o
    WHERE stereotype = 'Process'
    AND object_type = 'Package' 
    and (o.PDATA1=t.parent_ID 
    OR  o.PDATA1=t.package_ID)
)

答案 2 :(得分:0)

您可以两次加入t_object表;一次查找parent_ID关系,另一次查找package_ID关系。

SELECT p.package_ID
FROM t_package p
LEFT JOIN t_object oParent
ON p.parent_ID = oParent.PDATA1
AND oParent.stereotype = 'Process' 
AND oParent.object_type = 'Package'
LEFT JOIN t_object oPackage
ON p.parent_ID = oParent.PDATA1
AND oPackage.stereotype = 'Process' 
AND oPackage.object_type = 'Package'
WHERE oParent.PDATA1 IS NOT NULL OR oPackage.PDATA1 IS NOT NULL

答案 3 :(得分:0)

这真的取决于dbms。有些dbms在EXISTS子句上的执行计划比在IN子句上更好。

通常情况下,简单的联接是最好的。我不太喜欢这个解决方案,因为你的陈述更容易阅读,但关于速度,你可以尝试一下:

select distinct p.package_id
from t_package p
inner join t_object o on o.pdata1 in (p.package_id, p.parent_id)
  and o.stereotype = 'process' and o.object_type = 'package';

在您的情况下,您在t_object表中已有一些ID,其他必须从t_package获取。所以你也可以在这里尝试UNION。它可能更快,但我没有发现这种可能性。它取决于dbms,数据,索引等。

select package_id
from t_package
where parent_id in 
(
  select pdata1
  from t_object
  where stereotype = 'process' and object_type = 'package'
)
union
select pdata1
from t_object
where stereotype = 'process' and object_type = 'package';

或存在:

select package_id
from t_package
where exists
(
  select *
  from t_object
  where pdata1 = parent_id and stereotype = 'process' and object_type = 'package'
)
union
select pdata1
from t_object
where stereotype = 'process' and object_type = 'package';

答案 4 :(得分:0)

怎么样:

SELECT package_ID
FROM t_package, t_object
WHERE  stereotype = 'Process' AND object_type = 'Package'
and parent_ID = PDATA1
or package_ID = PDATA1