user_info要關聯查出其它社交表裡的資訊,但是其它社交表可能沒有這個使用者
select u.*, COALESCE(u.slogan, tw.description, i.bio, g.bio,tu.description) as bio from user_info u LEFT OUTER JOIN twitter_user tw ON u.user_name = tw.screen_nameLEFT OUTER JOIN instagram_user i ON u.user_name = i.usernameLEFT OUTER JOIN github_user g ON u.user_name = g.login LEFT OUTER JOIN tumblr_user tu ON u.user_name = g.name
引出了另外一個問題:postgresql應如何判斷Null 字元串
postgresql多表join 中用了 COALESCE
但是空的string還是會被選出來''
得再加個NULLIF判斷來解決
select u.*, COALESCE(NULLIF(u.slogan,''), NULLIF(tw.description,''), NULLIF(i.bio,''), NULLIF(g.bio,''), NULLIF(tu.description,'')) as bio from user_info u LEFT OUTER JOIN twitter_user tw ON u.user_name = tw.screen_nameLEFT OUTER JOIN instagram_user i ON u.user_name = i.usernameLEFT OUTER JOIN github_user g ON u.user_name = g.login LEFT OUTER JOIN tumblr_user tu ON u.user_name = g.name
於是改成了這樣
select u.*, COALESCE(NULLIF(u.slogan,''), NULLIF(tw.description,''), NULLIF(i.bio,''), NULLIF(g.bio,''), NULLIF(tu.description,'')) as bio from user_info u LEFT OUTER JOIN twitter_user tw ON u.user_name = tw.screen_nameLEFT OUTER JOIN instagram_user i ON u.user_name = i.usernameLEFT OUTER JOIN github_user g ON u.user_name = g.login LEFT OUTER JOIN tumblr_user tu ON u.user_name = g.name