如何在 MySQL select left join 中用 table2 列值替换 table1 列值

How to replace table1 column value with table2 column value in MySQL select left join

假设我有两个 MySQL 表:

table1(模板) 列:id_template、名称、col3、col4、...

table2(别名) 列:id_alias、id_template_orig、id_user、别名

我想 select table1(模板)中的一行,包括所有列 (*)。 在同一个 select 语句中,我想检查当前用户是否在 table2 中保存了原始模板名称的别名(别名)。 使用 LEFT JOIN 将别名列包含在结果行中没有问题,但我想知道是否有办法用 table2 别名值替换已经从 table1 selected 的原始名称列值。

所以这是 select 到目前为止:

SELECT table1.*, table2.alias, 
CASE WHEN table2.alias IS NULL THEN table1.name ELSE table2.alias END name 
FROM table1
LEFT JOIN table2 ON table2.id_template_orig=table1.id_template 
WHERE table1.id_template='1' 

除了它 returns 两个名称列而不是用第二个替换第一个

之外,这几乎可以正常工作

我知道 select table1.* 的所有列不是最佳做法,我的目标可以通过使用 select id_template、col3、col4 来实现, ... 来自 table1 但有时 * 只会让事情变得更容易。

不幸的是,在 MySQL 到 select * 中没有选项,但是 一列 - 例如在 BigQuery 中,它支持select * except (name).

您有两个选择:

  • 不要使用select table1.*;相反,枚举所有你想要的列,期望 name

  • 使用select *,并为生成的列指定一个不同的别名。

第二个选项可能是您的最佳选择,因为您明确表示要保留 select table1.*。它看起来像:

select t1.*, t2.alias, coalesce(t2.alias, t1.name) as new_name 
from table1 t1
left join table2 t2 on t2.id_template_orig = t1.id_template 
where t1.id_template = 1 

备注:

  • coalesce() 可以在这里替换你的 case 表达式

  • table 别名使查询更易于编写和阅读