SQL Union:将选择结果与直接值合并

时间:2014-07-16 09:14:27

标签: sql

在我的数据模型中,我有“部分”和“组件”,它们之间是N:M的关系。一部分可用于0:N组件,一个组件可使用0:N部分。

我想准备一个SQL来搜索“part”行,可以是部件ID或组件ID。 (我知道这不是最优的,但现在这些是我的条件。)

所以,我的第一次尝试尝试使用UNION(http://www.w3schools.com/sql/sql_union.asp

SELECT *
FROM part
WHERE part.id IN (
    ('abc', 'def') -- IDs of parts
    UNION (  -- IDs of parts that correspond to components with those IDs
        select part.id
        from component
        ... joins for the many-to-many: component-component2part-part
        where component.id in ('abc', 'def') -- same values as before
    )
)

此查询崩溃,可能是因为UNION子句的左侧部分不是查询的结果,而是直接值('abc', 'def'),并且它不能与子查询的结果合并。

我目前的解决方法是:

SELECT *
FROM part
WHERE (
    part.id IN ('abc', 'def') -- IDs of parts
    OR
    part.id IN ( -- IDs of parts that correspond to components with those IDs
        select part.id
        from component
        ... joins for the many-to-many: component-component2part-part
        where componend.id in ('abc', 'def') -- same values as before
    )
)

并且它有效,但可能这不是最有效的方法。有什么想法或暗示吗?提前谢谢。

该查询应该适用于SQL Server,Oracle和SQLite

2 个答案:

答案 0 :(得分:1)

如果您在第一组中有许多ID,则第二种方法是最佳方法 否则你可以做到

SELECT 'abc'
UNION
SELECT 'def'
UNION (
    select part.id
    from component
    ...
)

答案 1 :(得分:1)

如果我理解正确,你有一个id'abc',可能是一个部分的id,一个组件的id或两者兼而有之。你想要零件'abc'的零件信息和零件'abc'的零件信息。

基于这种理解,您需要具有匹配ID的部件列表以及具有相同ID的部件列表。然后将它们结合在一起。

select p.*
from   part p
where  p.id in( 'abc', 'def' )
union
select p.*
from   component c
join   part2components pc
  on   pc.Component_id = c.id
join   part p
  on   p.id = pc.Part_id
where  c.id in( 'abc', 'def' );
相关问题