简体   繁体   English

MySQL 查询 - 如何根据多列内连接的一列获取唯一行

[英]MySQL Query - How get unique rows based on one column of multiple column inner join

I have a query which selects members and the groups they are in for an organization.我有一个查询,它为组织选择成员和他们所在的组。 So a member can be in multiple groups.所以一个成员可以在多个组中。 The purpose of the query is to get all members that are in the selected groups.查询的目的是获取所选组中的所有成员。 But I only want a member returned once, along with only one of the group names.但我只希望一个成员返回一次,以及一个组名。 I do not want all the group names they belong to.我不想要他们所属的所有组名。

For instance below is list of members and the groups they are in:例如下面是成员列表和他们所在的组:
Mbr Grp Mbr组
1 -- G1 1 -- G1
1 -- G2 1 -- G2
2 -- G2 2 -- G2
2 -- G3 2 -- G3
3 -- G4 3 -- G4

The desired result is a member and one group they are in:期望的结果是他们所在的一个成员和一个组:
1 -- G1 1 -- G1
2 -- G2 2 -- G2
3 -- G4 3 -- G4

I have the following query working which returns the list of members and groups they are in, for each member / group combination:我有以下查询工作,它为每个成员/组组合返回他们所在的成员和组的列表:

```
SELECT ogm.group_id, ogm.member_id,  
      FROM org_group_member ogm 
INNER JOIN org_group og ON ogm.group_id
     WHERE ogm.group_id IN ('1', '2', '3')
  GROUP BY ogm.group_id, ogm.member_id
  ORDER BY ogm.group_id

```

This results in the first list I showed above.这导致了我在上面显示的第一个列表。 But I want the desired list.但我想要想要的清单。
I know how to limit query to unique member ids, but I do not know how to include only group id.我知道如何将查询限制为唯一的成员 ID,但我不知道如何仅包含组 ID。

What must I add to my query to achieve the results I desire?我必须在查询中添加什么才能获得我想要的结果?

You can use aggregation:您可以使用聚合:

SELECT ogm.member_id, ANY_VALUE(ogm.group_id),   
FROM org_group_member ogm JOIN
     org_group og
     ON ogm.group_id
WHERE ogm.group_id IN (1, 2, 3)
GROUP BY ogm.member_id;

Note that the group_id is probably a number, which is why I removed the single quotes.请注意, group_id可能是一个数字,这就是我删除单引号的原因。 Only use single quotes for string and date constants.仅对字符串和日期常量使用单引号。

I found the answer to my question.我找到了我的问题的答案。 I should have only included the ogm.member_id in the GROUP BY clause.我应该只在 GROUP BY 子句中包含 ogm.member_id。 Then I only got each member once with the first group they were found in.然后我只让每个成员在他们被发现的第一组中获得一次。

SELECT ogm.group_id, ogm.member_id,  
      FROM org_group_member ogm 
INNER JOIN org_group og ON ogm.group_id
     WHERE ogm.group_id IN ('1', '2', '3')
  GROUP BY ogm.member_id
  ORDER BY ogm.group_id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM