简体   繁体   English

MySQL - 左连接......在......喜欢

[英]MySQL - Left join … on … LIKE

I have 2 tables 我有2张桌子

On table "Users", each user has a number of skills. 在“用户”表上,每个用户都有许多技能。 They are found on a single column and are concatenated. 它们存在于单个列中并连接在一起。 On table "Skills", each skill has an associated label. 在表格“技能”上,每项技能都有一个相关的标签。

It happens that some users have skills that are not referenced on table "Skills" anymore. 碰巧有些用户拥有的技能不再在表“技能”上引用了。

The select I'd like to do should list all records on table users that contain a skill that is not referenced anymore on table skills. 我想要做的选择应列出表用户的所有记录,这些用户包含不再参考表技能的技能。

I was trying to do something like: 我试图做一些像:

SELECT user_id 
FROM USERS LEFT JOIN SKILLS 
ON USERS.skills = SKILLS.skill_id 
WHERE SKILLS.skill_id = null

However, the statement ON USERS.skills = SKILLS.skill_id does not fit my needs. 但是, USERS.skills = SKILLS.skill_id上的声明不符合我的需要。 The column USERS.skills contains the skill_id concatenated. USERS.skills列包含连接的skill_id。

I tried to replace that bit by ON USERS.skills LIKE SKILLS.skill_id but it still feels wrong and the query runs forever... 我试图通过ON USERS.skills LIKE SKILLS.skill_id替换那个位但是它仍然感觉不对而且查询永远运行...

Could you please enlighten me. 能不能请你开导。

You can't do that in this way without programming. 没有编程,你不能以这种方式做到这一点。 There are two possible ways: 有两种可能的方法:

  1. Read the skills in a text-string and split it and use another statement to read the kills (use the SQL: "WHERE id in (1,2,3)") 读取文本字符串中的技能并将其拆分并使用另一个语句来读取杀死(使用SQL:“WHERE id in(1,2,3)”)
  2. Use a link-Table. 使用链接表。 You must have the dependencies in a third table, the table mus have the fields: UserId and SkillId. 您必须在第三个表中具有依赖项,表格中包含以下字段:UserId和SkillId。 and if a User have 3 skills the third table must have 3 entries. 如果用户有3个技能,则第三个表必须有3个条目。 Than you can select them with a simple SQL-Statement 您可以使用简单的SQL语句选择它们

Ideally you should normalize the schema. 理想情况下,您应该规范化架构。

For now, you can use concatenation for using like and length and replace to find the number of items in the comma separated string. 目前,您可以使用串联来使用likelength并使用replace来查找逗号分隔字符串中的项目数。

select *
from users u
where length(u.skills) - length(replace(u.skills, ',', '')) + 1 <> (
        select count(*)
        from skills s
        where concat (', ',u.skills,',') like concat ('%, ',s.skill_id,',%')
        );

Demo 演示

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

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