2017-04-21 169 views
1

我是新來的SQL和我有一個非常基本的查詢:MySQL COALESCE在內部連接查詢中?

SELECT role.name AS role, 
     `username`, 
     game.name AS favorite_game, 
     `reg_date`, 
     `other_game` 
FROM `user` 
INNER JOIN role 
ON user.role = role.rid 
INNER JOIN game 
ON user.favorite_game = game.gid 
ORDER BY role.weight DESC, user.reg_date ASC 

它包含三個表userrolegame

user表中,列favorite_game可以爲空。如果是這種情況,我想顯示other_game的內容,而不是game表中的名稱。

也是如此。 other_games可以爲空,我想獲得遊戲的名稱。

一列總是有一個值,所以它們不能同時爲空。

我該如何做到這一點?我聽說過COALESCE,但我不知道如何在查詢中使用它,如果我應該的話。

+1

請發表您的表格的文章結構(文字) – etsa

回答

3

是的,​​3210正是你所需要的。它的工作原理是兩個參數,如果不爲空則返回第一個參數,否則返回第二個參數。

從您編寫查詢的方式來看,我假定沒有表名稱作爲前綴的字段來自user表。如果是這樣的話,你需要用gameleft join(如果沒有相關的行):

SELECT tr.name AS role, 
     tu.username, 
     coalesce(tg.name, tu.other_game) AS favorite_game, 
     tu.reg_date 
FROM user tu 
JOIN role tr 
ON  tu.role = tr.rid 
LEFT JOIN 
     game tg 
ON  tu.favorite_game = tg.gid 
ORDER BY tr.weight DESC, 
     tu.reg_date ASC 
+0

這正是我所需要的。謝謝! – Marlon

+0

不客氣:) –

2

對於這一點,你需要LEFT JOIN博弈兩次,使用IFNULL選擇相應的值,例如:

SELECT role.name AS role, 
     `username`, 
     IFNULL(fg.name, og.name) AS favorite_game, 
     IFNULL(og.name, fg.name) AS other_game, 
     `reg_date`, `other_game` 
FROM `user` 
INNER JOIN role 
ON user.role = role.rid 
LEFT JOIN game fg 
ON user.favorite_game = fg.gid 
LEFT JOIN game og 
ON user.other_game = og.gid 
ORDER BY role.weight DESC, user.reg_date ASC 

Here'sIFNULL的文檔。

1

您也可以使用case語句。

SELECT 
role.name AS role, 
`username`, 
(CASE WHEN game.name IS NOT NULL THEN game.name 
WHEN game.name IS NULL THEN other_game END) AS favorite_game, 
`reg_date` 
FROM `user` 
INNER JOIN role 
ON user.role = role.rid 
INNER JOIN game 
ON user.favorite_game = game.gid 
ORDER BY role.weight DESC, user.reg_date ASC;