查询与另一列的关系表

时间:2011-07-13 22:56:36

标签: mysql

我有两个表,实体和组件,每个都有一个名称和唯一ID。第三个表映射这两个称为构造的ID之间的多对多关系,包含两列,entity_ID和component_ID。实体由若干组件组成。因此,如果构造表看起来像这样:

+----------+---------------+
|entity_id |  component_id |
+----------+---------------+
|        1 |             1 | 
|        1 |             2 | 
|        2 |             2 | 
|        2 |             6 | 
+----------+---------------+

实体1由组件1,2组成,而实体2由2和6组成。我正在处理的应用程序还有一个包含所有可用组件ID的可用表。我的问题是,如何查询数据库以返回严格按可用表中的组件构造的实体?在给定的示例中,如果1,2和6都在可用表中,则应返回实体1和2。否则,如果2不在可用表中(但是1和6),则不返回任何内容。我是MySQL的新手,所以如果你能解释一下那个很棒的逻辑。

3 个答案:

答案 0 :(得分:2)

我测试了@ Abdullah的子查询,确实与我想要的相反。经过一些测试后,我最终得到了嵌套查询,这些查询为我提供了我想要的东西:

select distinct entity_id from construction 
where entity_id not in (
    select entity_id from construction c left outer join available a on a.id = c.component_id 
    where a.id is null 
);

答案 1 :(得分:1)

我没试过,但你可以试一试。

select * from construction c
where not exists (
    select * from construction c2 left outer join available a on a.id = c2.component_id
    where c2.entity_id = c.entity_id and a.id is null
)

在not exists部分中,我基本上选择所有实体E,当你加入E时,它的组件返回至少一个空组件。

<强>更新

要进行问题排查,请查看内部查询是否为您提供了所期望的内容:

select * from construction c2 left outer join available a on a.id = c2.component_id
where a.id is null

答案 2 :(得分:0)

试试这个:

SELECT e.entity_id, e.name                  --- Show all entities
FROM entity AS e
WHERE NOT EXISTS                            --- for which there not exists
      ( SELECT *                            --- any component that
        FROM construction AS c              --- they need for the construction
        WHERE c.entity_id = e.entity_id     
          AND c.component_id NOT IN         --- and it's not 
                ( SELECT component_id
                  FROM available            --- available
                )
      )

说明:显示所有不存在任何组件的实体,但不可用。