如果给定列 (year_id) 没有值 (null),我如何将两列合并为一列
表 1
id txt year_id date
----------------------------------
1 text1 1
2 text2 2
3 text3 3
4 text4 2013-01-02
5 text5 2013-01-03
表2
id year
----------------
1 2009
2 2010
3 2011
4 2012
我需要这样的结果
id txt merge_column
-------------------------
1 text1 2009
2 text2 2010
3 text3 2011
4 text4 2013-01-02
5 text5 2013-01-03
提前谢谢你,这个查询让我的头脑复杂化了..谢谢
最佳答案
首先使用 COALESCE()
或 IFNULL()
连接两个表。
SELECT a.id,
a.txt,
COALESCE(b.year, a.date) merge_column
FROM table1 a
LEFT JOIN table2 b
ON a.year_id = b.id
关于如果给定列没有值,则 MYSQL 合并为一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16704651/