简体   繁体   English

MySQL:使用 id 将 table2 中的条目与 table1 中的条目匹配,然后将匹配项作为新列插入 table2

[英]MySQL: Match entry in table2 to those in table1 using an id, then insert matches as new column into table2

Suppose I have two datasets of students.假设我有两个学生数据集。 I want to match students in one dataset to another.我想将一个数据集中的学生与另一个数据集进行匹配。 The match criteria is whether the first 4 letters of the first name, last 4 letters of last name, and the first 4 letters of the first word in the high school name match.匹配标准是名字的前4个字母、姓氏的后4个字母、高中名字第一个单词的前4个字母是否匹配。 If these are all true, we assume that the students are the same.如果这些都是真的,我们假设学生是一样的。

I am able to accomplish this using我能够使用

SELECT t1.`Full Name`, t1.`uid_hist`, t2.`fullname`, t2.`hsname`, t1.`High School`
FROM table1 t1
LEFT JOIN table2 t2
on SUBSTRING(REGEXP_SUBSTR(LOWER(t2.fullname), '^[a-z]*?[^a-z]'), 1, 4) = SUBSTRING(REGEXP_SUBSTR(LOWER(t1.`Full Name`), '^[a-z]*?[^A-z]'), 1, 4)
and SUBSTRING(REGEXP_SUBSTR(LOWER(t2.fullname), '[^a-z][a-z]*?$'), -4) = SUBSTRING(REGEXP_SUBSTR(LOWER(t1.`Full Name`), '[^a-z][a-z]*?$'), -4)
and SUBSTRING(REGEXP_SUBSTR(LOWER(t2.hsname), '^[a-z]*?[^a-z]'), 1, 4) = SUBSTRING(REGEXP_SUBSTR(LOWER(t1.`High School`), '^[a-z]*?[^a-z]'), 1, 4) 

This is pretty slow, so I am also curious if there is a better way, but it appears to work as intended.这很慢,所以我也很好奇是否有更好的方法,但它似乎按预期工作。

Now, my question is, how do I go about inserting the matched 'uid's from table 1 as a new column in table2?现在,我的问题是,如何将表 1 中匹配的“uid”作为表 2 中的新列插入? That is, if there is a student who was matched to a student in table1, then the unique identifier for that student in table1 will be in the column 'match'.也就是说,如果有一个学生与 table1 中的学生匹配,则 table1 中该学生的唯一标识符将在列“匹配”中。 For students that are not matched, 'match' will simply be null.对于不匹配的学生,'match' 将简单地为空。

If a row in table2 is matched to more than one student in table1, let's say we repeat the row in table2, except with different values for 'match'.如果 table2 中的一行与 table1 中的多个学生匹配,假设我们重复 table2 中的行,除了“匹配”的不同值。

Is there any straightforward way to accomplish this?有没有直接的方法来实现这一点? I am very new to MySQL and not sure how to proceed我对 MySQL 很陌生,不知道如何继续

I don't think you need regular expressions for this:我认为您不需要正则表达式:

SELECT t1.`Full Name`, t1.`uid_hist`, t2.`fullname`, t2.`hsname`, t1.`High School`
FROM table1 t1 LEFT JOIN
     table2 t2
     ON LEFT(t2.fullname, 4) = LEFT(LOWER(t1.`Full Name`) AND
        RIGHT(t2.fullname, 4) = RIGHT(LOWER(t1.`Full Name`) AND
        LEFT(t2.`High School`, 4) = LEFT(LOWER(t1.`High School`)

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

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