从右边 table 条件得到左边 table 行
get left table rows from right table conditions
我有三个这样的表:
人:
编号 |姓名 |性别
--------------------------
1乔男
2 大牛男
3莎拉女
person_skills:
person_id | skill_id
--------------------------
1 1
1 2
1 3
2 1
2 2
...
技能:
编号 | skill_name
----------------------
1 写作
2 编程
3 唱歌
...
当我在查询中发送他们的一项技能时,我需要获得他们的所有技能。
这是我的代码:
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
我要结果:
姓名 |性别 | skill_name | skill_id
--------------------------------------------
乔男写作1
编程 2
唱歌 3
但是这段代码return只有skill_id“3”和skill_name"Singing".
提前致谢。
您需要引用一些 table 两次。
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
旁注:我没管它,但在某些配置下您的分组标准可能会出现问题。
...以及替代方案,如果您不喜欢额外的 table 引用,但不太可能更快:
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;
我有三个这样的表:
人:
编号 |姓名 |性别 -------------------------- 1乔男 2 大牛男 3莎拉女
person_skills:
person_id | skill_id -------------------------- 1 1 1 2 1 3 2 1 2 2 ...
技能:
编号 | skill_name ---------------------- 1 写作 2 编程 3 唱歌 ...
当我在查询中发送他们的一项技能时,我需要获得他们的所有技能。
这是我的代码:
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
我要结果:
姓名 |性别 | skill_name | skill_id -------------------------------------------- 乔男写作1 编程 2 唱歌 3
但是这段代码return只有skill_id“3”和skill_name"Singing".
提前致谢。
您需要引用一些 table 两次。
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
旁注:我没管它,但在某些配置下您的分组标准可能会出现问题。
...以及替代方案,如果您不喜欢额外的 table 引用,但不太可能更快:
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;