有没有办法替换 SQL 中另一个 table 上出现的所有值?
Is there a way to replace all values that appear on another table in SQL?
我需要查询以获取所有分数为 70 或更高的记录,并将所有昵称替换为相应的专有名称。我正在使用 MySQL
Table一个
name
score
Nick
75
Kate
76
Robert
49
John
91
Jenny
87
Bill
29
Gabrielle
57
Taylor
88
Joseph
68
所需的输出应如下所示:
查询结果
name
score
Nicholas
75
Kate
76
John
91
Jennifer
87
Taylor
88
请注意名字 Nick 和 Jenny 被替换了。
目前,我的做法是使用 REPLACE
,但它的扩展性不是很好,所以我想知道是否有办法从 Table B 获取昵称并使用它在我的查询中。我当前的查询如下所示:
SELECT
-- repeat this for every nickname
REPLACE(REPLACE(name,'Nick','Nicholas'),'Jenny','Jennifer') AS name,
score
FROM
table_a
WHERE
score >= 70;
Table B
nickname
proper_name
Nick
Nicholas
Jenny
Jennifer
Bill
William
Gaby
Gabrielle
您使用左联接查找 table_a 中每一行的正确名称。如果找不到正确的名称,它将为空,因此您使用 coalesce 来使用原始名称:
select coalesce(proper_name, name) as name, score
from table_a
left join table_b on table_b.nickname=table_a.name
where score >= 70
我需要查询以获取所有分数为 70 或更高的记录,并将所有昵称替换为相应的专有名称。我正在使用 MySQL
Table一个
name | score |
---|---|
Nick | 75 |
Kate | 76 |
Robert | 49 |
John | 91 |
Jenny | 87 |
Bill | 29 |
Gabrielle | 57 |
Taylor | 88 |
Joseph | 68 |
所需的输出应如下所示:
查询结果
name | score |
---|---|
Nicholas | 75 |
Kate | 76 |
John | 91 |
Jennifer | 87 |
Taylor | 88 |
请注意名字 Nick 和 Jenny 被替换了。
目前,我的做法是使用 REPLACE
,但它的扩展性不是很好,所以我想知道是否有办法从 Table B 获取昵称并使用它在我的查询中。我当前的查询如下所示:
SELECT
-- repeat this for every nickname
REPLACE(REPLACE(name,'Nick','Nicholas'),'Jenny','Jennifer') AS name,
score
FROM
table_a
WHERE
score >= 70;
Table B
nickname | proper_name |
---|---|
Nick | Nicholas |
Jenny | Jennifer |
Bill | William |
Gaby | Gabrielle |
您使用左联接查找 table_a 中每一行的正确名称。如果找不到正确的名称,它将为空,因此您使用 coalesce 来使用原始名称:
select coalesce(proper_name, name) as name, score
from table_a
left join table_b on table_b.nickname=table_a.name
where score >= 70