[英]How to replace table1 column value with table2 column value in MySQL select left join
假设我有两个 MySQL 表:
table1(模板)列:id_template、name、col3、col4、...
table2(别名)列:id_alias、id_template_orig、id_user、别名
我想从 table1(模板)中选择一行,包括所有列 (*)。 在同一个 select 语句中,我想检查当前用户是否为 table2 中的原始模板名称保存了别名(别名)。 使用 LEFT JOIN 获取包含在结果行中的别名列没有问题,但我想知道是否有办法将已经从 table1 中选择的原始 name 列值替换为 table2 别名值。
所以这是到目前为止的选择:
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'
这几乎可以正常工作,只是它返回两个名称列而不是用第二个替换第一个
我知道用 table1.* 选择所有列并不是最佳实践,我的目标将通过使用 select id_template, col3, col4, ... from table1 来实现,但有时 * 只是让事情变得更容易。
不幸的是,在 MySQL 中没有选择*
选项,只有一列 - 例如在 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
表达式
表别名使查询更易于读写
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.