从右表条件获取左表行

时间:2018-12-07 19:00:44

标签: mysql sql group-by left-join group-concat

我有三个这样的表:

人:

  id   |  name  |  gender
---------------------------
  1       Joe       male
  2       Daniel    male
  3       Sarah     female

person_skills:

  person_id  |  skill_id
---------------------------
      1            1
      1            2
      1            3
      2            1
      2            2
...

技能:

  id  |  skill_name
-----------------------
  1       Writing
  2       Programming
  3       Singing
...

当我在查询中只发送某人的技能时,我需要获得他们的所有技能。

这是我的代码:

SELECT a.name, a.gender, 
       GROUP_CONCAT(DISTINCT c.skill_name), 
       GROUP_CONCAT(DISTINCT c.id as skill_id) 
FROM persons a 
LEFT JOIN person_skills b ON b.person_id = a.id 
LEFT JOIN skills c ON c.id = b.skill_id
WHERE b.skill_id = 3 GROUP BY a.id 

我想要结果:

 name  |  gender  |  skill_name  |  skill_id
----------------------------------------------
 Joe      male       Writing           1
                     Programming       2
                     Singing           3

但是此代码仅返回skill_id“ 3”和skill_name“ Singing”。

谢谢。

1 个答案:

答案 0 :(得分:0)

您需要两次引用一些表。

SELECT p.name, p.gender, 
       GROUP_CONCAT(DISTINCT s.skill_name), 
       GROUP_CONCAT(DISTINCT s.id as skill_id) 
FROM person_skills AS ps0
INNER JOIN persons AS p ON ps0.person_id = p.id
LEFT JOIN person_skills ps ON p.id = ps.person_id 
LEFT JOIN skills s ON s.id = ps.skill_id
WHERE ps0.skill_id = 3 
GROUP BY p.id 

旁注:我没有理会,但是在某些配置下您的分组标准可能会出现问题。

...以及另一种选择,如果您不喜欢额外的表引用,但是不太可能更快:

SELECT p.name, p.gender, 
       GROUP_CONCAT(DISTINCT s.skill_name), 
       GROUP_CONCAT(DISTINCT s.id as skill_id) 
FROM persons AS p 
LEFT JOIN person_skills ps ON p.id = ps.person_id 
LEFT JOIN skills s ON s.id = ps.skill_id
GROUP BY p.id 
HAVING COUNT(CASE s.skill_id WHEN 3 THEN 1 ELSE NULL) > 0;