3

有 3 个表DEVELOPERMANAGERPROJECT

create table DEVELOPER(id int(4), lastname varchar(40), project_id int(4));

create table MANAGER(id int(4), lastname varchar(40), project_id int(4));

create table PROJECT(id int(4), name varchar(40));

PROJECT 和 DEVELOPER 之间的关系是一对多的,PROJECT 和 MANAGER 之间的关系是一对一的。

存储在数据库中的所有姓氏都是唯一的。经理可以同时是同一项目的开发人员。(在这种情况下,他的数据存储在两个表中)。

我想从我的数据库中接收特定项目的所有开发人员和经理的列表,格式如下:

编号| 姓氏| isManager

我认为它适合以下查询:

SELECT id, lastname, false AS isManager FROM developer WHERE project_id = 314
UNION 
SELECT id, lastname true AS isManager FROM manager WHERE project_id = 314 

但是如果他也是特定项目的开发人员,我不想有两行经理的数据!我想离开属性 isManager 为真的那一行。请建议我正确的查询来解决这个问题!

4

2 回答 2

3

您可以FULL OUTER JOIN为此目的使用:

SELECT COALESCE(m.id, d.id) AS id -- m comes first!
     , lastname                   -- lastname consolidated by USING
     , CASE WHEN m.id IS NOT NULL THEN TRUE ELSE FALSE END AS is_manager
FROM   developer d
FULL   OUTER JOIN manager m USING (lastname, project_id)
WHERE  project_id = 314;

但首先您可能会考虑@a_horse_with_no_name关于您的数据库设计的建议。

于 2013-05-11T11:47:56.107 回答
0

您可以group by消除重复:

select  id
,       lastname
,       max(IsManager) as IsManager
from    (
        select  id
        ,       lastname
        ,       project_id
        ,       0 as IsManager 
        from    developer 
        union all
        select  id
        ,       lastname
        ,       project_id
        ,       1
        from    manager
        ) SubQueryAlias
where   project_id = 314
group by
        id
,       lastname
于 2013-05-11T11:17:50.483 回答