针对多对多的复杂MySQL查询

时间:2013-12-14 05:09:29

标签: mysql sql many-to-many one-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       | Total Resources      |
| A              | 3                    |
| B              | 1                    |
| C              | 1                    |

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

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

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

问候。

2 个答案:

答案 0 :(得分:0)

请尝试以下查询。

SELECT org_name, COUNT(DISTINCT res_id)
FROM organization, members, member-resource
WHERE members.mem_id = member-resource.mem_id
AND organization.org_id = members.org_id
GROUP BY org_id, org_name

答案 1 :(得分:0)

这比你想象的要简单得多,特别是因为你甚至不需要resource表:

SELECT o.org_name, COUNT(DISTINCT mr.res_id) TotalResources
FROM member_resource mr
JOIN members m ON mr.mem_id = m.mem_id
JOIN organization o ON m.org_id = o.org_id
GROUP BY o.org_id

输出:

| ORG_NAME | TOTALRESOURCES |
|----------|----------------|
|        A |              3 |
|        B |              1 |
|        C |              1 |

小提琴here