MySQL Query将两个表连接在一起,并获得一行与组合数据

时间:2015-04-16 13:59:01

标签: mysql sql

我的数据库模型很差,有两个表(groupownergroupmembers),数据几乎相同。我想创建一个组合它们的视图,并按用户对它们进行分组。

使用以下查询...

 SELECT 'group' AS resourceType, gm.gid AS resource_id, gm.personid AS account_id, false AS isManager, true AS isMember
 FROM data.groupmembers gm
     UNION
 SELECT 'group' AS resourceType, gn.gid AS resource_id, gn.owner AS account_id, true AS isManager, false AS isMember
 FROM data.groupowner gn
     ORDER BY resource_id ASC, account_id ASC;

......我得到这样的东西:

resourceType | resource_id | account_id | isManager | isMember
------------ | ----------- | ---------- | --------- | --------
group        | 105         | 506        | 1         | 0
group        | 105         | 506        | 0         | 1
etc...

..当我想要的是这个(从两个表或一个或另一个表中合并)时:

resourceType | resource_id | account_id | isManager | isMember
------------ | ----------- | ---------- | --------- | --------
group        | 105         | 506        | 1         | 1
etc...

有没有办法用MySQL查询来完成这个?

2 个答案:

答案 0 :(得分:1)

我想你想要一个join而不是union all。假设所有所有者都是成员,那么这应该是并且是" view"兼容MySQL:

SELECT 'group' AS resourceType, gm.gid AS resource_id, gm.personid AS account_id,
       (gn.personid is not null) AS isManager, true AS isMember
FROM data.groupmembers gm LEFT JOIN
     data.groupowner gn
     ON gm.gid = gn.gid and
        gm.personid = gn.personid;

另一种方法使用相关子查询:

select gm.*,
       (exists (select 1
                from data.groupowner gn
                where gm.gid = gn.gid and gm.personid = gn.personid
       ) as IsManager
from data.groupmembers;

如果业主是会员,我不确定为什么你需要" isMember"列。

编辑:

如果所有者不是成员,那么您将面临获得视图兼容逻辑的挑战。但是,这应该有效:

SELECT 'group' AS resourceType, gm.gid AS resource_id, gm.personid AS account_id,
       (gn.personid is not null) AS isManager, true AS isMember
FROM data.groupmembers gm LEFT JOIN
     data.groupowner gn
     ON gm.gid = gn.gid and
        gm.personid = gn.personid
UNION ALL
SELECT 'group', gn.gid, gn.personid,
       true, false
FROM data.groupowner gn
WHERE NOT EXISTS (SELECT 1
                  FROM data.groupmembers
                  WHERE gm.gid = gn.gid and gm.personid = gn.personid
                 );

答案 1 :(得分:0)

尝试将以下查询用于欲望输出

SELECT resourceType, resource_id, account_id, sum(isManager), sum(isMember) from
( SELECT 'group' AS resourceType, gm.gid AS resource_id, gm.personid AS account_id, 0 AS isManager, 1 AS isMember
 FROM data.groupmembers gm
     UNION
 SELECT 'group' AS resourceType, gn.gid AS resource_id, gn.owner AS account_id, 1 AS isManager, 0 AS isMember
 FROM data.groupowner gn
     ORDER BY resource_id ASC, account_id ASC) temp
group by  resource_id, account_id;