2016-05-10 49 views
1

使用該查詢中排除空獲得JSON結果如下圖所示的數據結構,的if/else列值選擇選擇表中,JSON

SELECT c.* , 
    row_to_json(mg.*) as media_gallery, 
    row_to_json(m.*) as media, 
    row_to_json(g.*) as gallery 
    FROM comment c 

    LEFT JOIN media m ON m.id = c.endpoint_id 
    .... join mg g table 

是它的列值可以基地選擇選擇表,也許這樣的語法,排除在media_gallery,媒體和畫廊的結果,如果是空

SELECT c.* , 
    CASE WHEN c.endpoint_code = 1 
    THEN 
    row_to_json(mg.*) as media_gallery, 
    row_to_json(m.*) as media, 
    END 

    CASE WHEN c.endpoint_code = 0 THEN 
    row_to_json(g.*) as gallery 
    END 

    FROM comment c 

    LEFT JOIN media m ON m.id = c.endpoint_id 
    .... join mg g table 

結果

rows: 
[ { id: 7, 
    endpoint_code: 0, 
    endpoint_id: 27, 
    status: 0, 

    media_gallery: null, 
    media: null, 
    gallery: 
    { id: 27, 
    status: 0, 
    create_date: 
    ... 

UPDATE

我也試過這個,但不行

COALESCE(row_to_json(mg.*), null) AS media_gallery, 
+0

'case'語句只返回一個** single **表達式。 –

+0

一個表達式... – jarlh

+0

@a_horse_with_no_name感謝您的回覆,我只是不明白:(我更新我的代碼庫在下面的Gordon Linoff答案,但仍然返回結果包含media_gallery,媒體或畫廊,沒有任何改變用例或不...你知道爲什麼以及如何修復它嗎? – user1575921

回答

0

難道這就是你想要什麼?

SELECT c.* , 
     (CASE WHEN c.endpoint_code = 1 THEN row_to_json(mg.*) END) as media_gallery, 
     (CASE WHEN c.endpoint_code = 1 THEN row_to_json(m.*) END) as media, 
     (CASE WHEN c.endpoint_code = 0 THEN row_to_json(g.*) END) as gallery 
. . . 
+0

感謝您的回覆我嘗試這個,但似乎沒有什麼不同,與不使用的情況下,它仍然返回結果像'media_gallery:空, 媒體:空, 畫廊: {id:27, status:0,'我只想返回畫廊或media_gallery,媒體...... – user1575921