1

指定された列 (year_id) に値がない (null) 場合、2 つの列を 1 つの列にマージするにはどうすればよいですか

表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

前もってありがとう、このクエリは私の心を複雑にします..ありがとう

4

3 に答える 3

3

COALESCE()最初にorを使用して両方のテーブルを結合します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
于 2013-05-23T02:25:38.730 に答える
1
SELECT t1.id, txt, IFNULL(date, year) merge_column
FROM table1 t1
LEFT JOIN table2 t2 ON t1.year_id = t2.id
于 2013-05-23T02:26:14.407 に答える