我通过UserSkills表连接了用户和技能表,用于多对多关系。以下是表格中的内容:
Users (id, username)
Skills (id, name)
UserSkills (user_id, skill_id)
我正在寻找一系列技能[' C#',' SQL']。所以我正在加入IN过滤操作,只获得那些我需要的用户。
SELECT (username, GROUP_CONCAT(Skills.name)) FROM Users
JOIN UserSkills ON Users.id = UserSkills.user_id
JOIN Skills ON Skills.id = UserSkills.skill_id AND Skills.name IN ('C#', 'SQL')
GROUP BY Users.id
我希望获得相同的用户列表,但拥有他们所有的技能,而不仅仅是我正在寻找的那些。例如:
In my case I get: username: 'joe' | skills: 'C#', 'SQL'
I want to get: username: 'joe' | skills : 'C#', 'SQL', 'JavaScript', 'NodeJS'
请帮忙。
答案 0 :(得分:1)
最直接的方式是第二次加入:
SELECT u.username, GROUP_CONCAT(DISTINCT userS.name)
FROM Users AS u
INNER JOIN UserSkills AS us ON u.id = us.user_id
INNER JOIN Skills AS filterS ON filterS.id = us.skill_id AND filterS.name IN ('C#', 'SQL')
INNER JOIN Skills AS userS ON userS.id = us.skill_id
GROUP BY u.id
但是你需要GROUP_CONCAT中的DISTINCT,因为过滤技能基本上会与用户技能交叉加入。另外值得注意的是,此查询会为用户提供任何指定的技能,而不是全部。这是一个更好的解决方案:
SELECT u.username, GROUP_CONCAT(s.name) AS skils
, COUNT(CASE WHEN s.name IN ('C#', 'SQL') THEN 1 ELSE NULL END) AS matchedSkillCount
FROM Users AS u
INNER JOIN UserSkills AS us ON u.id = us.user_id
INNER JOIN Skills AS s ON s.id = us.skill_id
GROUP BY u.id
HAVING matchedSkillCount > 0 -- You can replace 0 with the number of matches you want
;
...但是在非常大的数据库中,上述情况可能会变得昂贵;其他几种选择:
SELECT u.username, GROUP_CONCAT(DISTINCT userS.name)
FROM Skills AS filterS
INNER JOIN UserSkills AS ufs ON filterS.id = ufs.skill_id
INNER JOIN Users AS u ON ufs.user_id = u.id
INNER JOIN UserSkills AS us ON u.id = us.user_id
INNER JOIN Skills AS userS ON us.skill_id = userS.id
WHERE filterS.name IN ('C#', 'SQL')
GROUP BY u.id;
SELECT u.username, GROUP_CONCAT(s.name) AS skils
FROM Users AS u
INNER JOIN UserSkills AS us ON u.id = us.user_id
INNER JOIN Skills AS sON s.id = us.skill_id
WHERE u.id IN (
SELECT DISTINCT ufs.user_id
FROM Skills AS filterS
INNER JOIN UserSkills AS ufs ON filterS.id = ufs.skill_id
WHERE filterS.name IN ('C#', 'SQL')
)
GROUP BY u.id
;
逻辑上,WHERE在连接后应用;但大多数RDBMS(如MySQL)通过使用WHERE条件来优化执行,以最小化连接在一起的行。
答案 1 :(得分:0)
select USERS.name,GROUP_CONCAT(Skills.name) from USERS join USERSKILLS on users.id =
USERSKILLS.user_id join skills on USERSKILLS.SKILL_ID = skills.ID and users.id in (
select distinct users.id from
users join USERSKILLS on users.id = USERSKILLS.user_id join skills on skills.id = userSkills.skill_id and
Skills.name IN ('C#', 'SQL'))
group by USERS.name;