简体   繁体   English

MySQL在有条件的情况下在一列中连接多行

[英]MySQL Join multiple rows in one column with condition

Tables 桌子

Person

ID|NAME |SURNAME
1 |James|Smith
2 |Jack |Sparrow

PeopleDepartment 人事部

IDPERSON|IDDEPARTMENT
1       |1
1       |2
2       |2

Department

ID|NAME
1 |customer_service
2 |store

Problem 问题

What I need to do is select people and its departments, filtering by one or more departments. 我需要做的是选择人员及其部门,并按一个或多个部门进行筛选。 Now I'm able to select all the people and their departments, but I can't filter the results by departments name: 现在,我可以选择所有人员及其部门,但是无法按部门名称过滤结果:

SELECT person.name, person.surname, GROUP_CONCAT(distinct department.name SEPARATOR ', ') as departments
LEFT JOIN peopledepartment ON person.id=department.idperson
INNER JOIN department ON peopledepartment.iddepartment=department.id

And the output with that query is: 该查询的输出为:

NAME |SURNAME|DEPARTMENTS
James|Smith  |customer_service, store
Jack |Sparrow|store

I need to filter that result by department.name='customer_service', so the result is only: 我需要按department.name ='customer_service'筛选结果,因此结果仅为:

NAME |SURNAME|DEPARTMENTS
James|Smith  |customer_service, store

Any ideas? 有任何想法吗? Thanks in advance! 提前致谢!

Use a having clause: 使用having子句:

SELECT p.name, p.surname,
       GROUP_CONCAT(distinct d.name SEPARATOR ', ') as departments
FROM person p INNER JOIN
     peopledepartment pd
     ON p.id = pd.idperson INNER JOIN
     department d
     ON pd.iddepartment = d.id
GROUP BY p.name, p.surname
HAVING SUM(d.name = 'customer_service') > 0;

Notes: 笔记:

  • The distinct is probably not necessary in group_concat() . group_concat()可能不需要distinct
  • Use table aliases. 使用表别名。 These make it easier to write and read the query. 这些使编写和读取查询变得更加容易。
  • You seem to have left out the from clause in your question. 您似乎没有在问题中使用from子句。
  • The having clause counts the number of rows that match the given department. having子句计算与给定部门匹配的行数。 The > 0 means that at least one such match exists. > 0表示存在至少一个这样的匹配项。

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

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