针对特定模式的多对多复杂MySQL查询

时间:2013-12-14 09:23:58

标签: mysql sql many-to-many

我搜索并浏览了类似于我的可用主题。但是,未能找到满足我的要求。因此,请在此处发布。

我有四张表如下:

"Organization" table:
--------------------------------
| org_id       | org_name      |
| 1            | A             |
| 2            | B             |
| 3            | C             |

"Members" table:
----------------------------------------------
| mem_id       | mem_name     | org_id       |
| 1            | mem1         | 1            |
| 2            | mem2         | 1            |
| 3            | mem3         | 2            |
| 4            | mem4         | 3            |

"Resource" table:
--------------------------------
| res_id       | res_name      |
| 1            | resource1     |
| 2            | resource2     |
| 3            | resource3     |
| 4            | resource4     |

"member-resource" table:
--------------------------------------------
| sl_no        | mem_id     | res_id       |
| 1            | 1          | 1            |
| 2            | 1          | 2            |
| 3            | 2          | 1            |
| 4            | 4          | 3            |
| 5            | 3          | 4            |
| 6            | 2          | 3            |
| 7            | 4          | 3            |

我想根据组织找出共享资源的总数。预期产出如下:

| org_name       | Shared Resources     |
| A              | 1                    |
| B              | 0                    |
| C              | 1                    |

我还想根据组织找出重复资源的总数。预期产出如下:

| org_name       | Duplicate Resources  |
| A              | 2                    |
| B              | 0                    |
| C              | 1                    |

在这方面的任何帮助都将受到高度赞赏。

问候。

1 个答案:

答案 0 :(得分:1)

要获取跨组织的共享资源总数,您可以尝试

SELECT o.org_name, COALESCE(q.total, 0) shared_resources
  FROM organization o LEFT JOIN
(
  SELECT m.org_id, COUNT(DISTINCT mr.res_id) total
    FROM member_resource mr JOIN members m
      ON mr.mem_id = m.mem_id
   WHERE EXISTS
  (
    SELECT *
      FROM member_resource mr2 JOIN members m2
        ON mr2.mem_id = m2.mem_id
     WHERE mr2.res_id = mr.res_id
       AND m2.org_id <> m.org_id
  )
   GROUP BY org_id
) q
     ON o.org_id = q.org_id

示例输出:

| ORG_NAME | SHARED_RESOURCES |
|----------|------------------|
|        A |                1 |
|        B |                0 |
|        C |                1 |

这是 SQLFiddle 演示


要获取跨组织的重复资源总数,您可以尝试

SELECT o.org_name, COALESCE(q.total, 0) duplicate_resources
  FROM organization o LEFT JOIN
(
  SELECT m.org_id, COUNT(DISTINCT mr.res_id) total
    FROM member_resource mr JOIN members m
      ON mr.mem_id = m.mem_id
   WHERE EXISTS
  (
    SELECT *
      FROM member_resource mr2
     WHERE mr2.res_id = mr.res_id
       AND mr2.sl_no <> mr.sl_no
  )
   GROUP BY org_id
) q
     ON o.org_id = q.org_id

示例输出:

| ORG_NAME | DUPLICATE_RESOURCES |
|----------|---------------------|
|        A |                   2 |
|        B |                   0 |
|        C |                   1 |

这是 SQLFiddle 演示