如果给定列没有值,MYSQL将合并到一列中
如果给定列(year_id)没有值(null),如何将两列合并到一列中 表1如果给定列没有值,MYSQL将合并到一列中,mysql,sql,Mysql,Sql,如果给定列(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 ye
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()
COALESCE()
或IFNULL()
连接两个表
select t1.id, t1.txt,
coalesce(date_format(t2.date, '%y-%m-%d'), cast(t2.year as varchar(32))
from table1 t1 left join
table2 t2
on t1.year_id = t2.id
您需要将这些值转换为通用类型。我认为字符串是最有可能的
select t1.id, t1.txt,
coalesce(date_format(t2.date, '%y-%m-%d'), cast(t2.year as varchar(32))
from table1 t1 left join
table2 t2
on t1.year_id = t2.id
很好,这太棒了!这就是我想在我的查询中看到的。。。苏伯伯!!很好,这太棒了!这就是我想在我的查询中看到的。。。苏伯伯!!
select t1.id, t1.txt,
coalesce(date_format(t2.date, '%y-%m-%d'), cast(t2.year as varchar(32))
from table1 t1 left join
table2 t2
on t1.year_id = t2.id