我是SQL的新手,我有一个非常基本的查询:
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
它包含三个表user
,role
和game
。
在user
表中,列favorite_game
可以为空。如果是这种情况,我想显示other_game
的内容,而不是game
表中的名称。
相反,相反。 other_games
可以为null,我想获得游戏的名称。
一列总是有一个值,因此它们不能同时为空。
我怎样才能做到这一点?我听说过COALESCE
,但我不知道如何在我的查询中使用它,如果我应该。
答案 0 :(得分:3)
是的,coalesce
正是您所需要的。它可以处理两个参数,如果它不为空则返回第一个参数,否则返回第二个参数。
从您编写查询的方式来看,我假设没有表名作为前缀的字段来自user
表。如果是这种情况,则需要left join
game
表(如果没有关联的行):
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
答案 1 :(得分: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's IFNULL
的文档。
答案 2 :(得分:1)
您也可以使用案例陈述。
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;