简体   繁体   English

从右表条件获取左表行

[英]get left table rows from right table conditions

I have three tables like this: 我有三个这样的表:

person: 人:

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

person_skills: person_skills:

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

skills: 技巧:

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

I need to get all the skills of persons when I just send one of their skills in my query. 当我在查询中仅发送某人的技能时,我需要获得他们的所有技能。

This is my code: 这是我的代码:

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 

I want the result: 我想要结果:

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

But this code return only skill_id "3" and skill_name "Singing". 但是此代码仅返回skill_id“ 3”和skill_name“ Singing”。

Thanks in advance. 提前致谢。

You'll need to reference some tables twice. 您需要两次引用一些表。

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 

Sidenote: I left it alone, but your grouping criteria can be problematic under certain configurations. 旁注:我没有理会,但是在某些配置下您的分组条件可能会出现问题。

...and alternative, if you averse to the extra table references, but unlikely to be faster is: ...以及另一种选择,如果您不喜欢多余的表引用,但是不太可能更快:

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;

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

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