我正在编写一个代码来从数据库中获取排名,将其放入表中并按顺序排序。问题在于我加入了几张桌子而且参加锦标赛的一些玩家甚至没有进入排名表(我有一个不同的桌子列出了球员名单)。目前,没有等级的玩家具有空值并且显示为这样。这可能没问题,但我需要按排名订购玩家。它看起来像这样:
问题是 - 是否存在将使例如5000中的空值和没有排名的玩家的语句显示在表格的底部。提前谢谢!
我的代码:
SELECT
*,
p1.surname AS 'p1surname',
p1.name AS 'p1name',
p2.surname AS 'p2surname',
p2.name AS 'p2name',
m1.rank AS 'm1rank',
m2.rank AS 'm2rank'
CASE
WHEN m1rank is NULL
THEN m1rank = '5000'
END,
CASE
WHEN m2rank is NULL
THEN m2rank = '5000'
END
FROM
alists_lv lv
JOIN
players p1 ON lv.player1_id = p1.id
JOIN
players p2 ON lv.player2_id = p2.id
LEFT JOIN
womensranking m1 ON lv.player1_id = m1.id
LEFT JOIN
womensranking m2 ON lv.player2_id = m2.id
WHERE
tournament_id = '$id' AND p1.gender = 'F'
ORDER BY
(m1rank + m2rank)
答案 0 :(得分:0)
我认为你拥有的很好,但是你需要在你的案例陈述中添加else语句:
当m1.rank为NULL时为例,m1.rank ='5000',否则为m1.rank END,
当m2.rank为NULL时为例,m2.rank ='5000',否则为m2.rank END
然后将这些相同的case语句添加到order by子句中。或者您可以为这些case语句添加别名,并将这些别名放在order by子句中。
答案 1 :(得分:0)
我解决了这个问题。使用COALESCE
SELECT *, p1.surname AS 'p1surname',
p1.name AS 'p1name',
p2.surname AS 'p2surname',
p2.name AS 'p2name',
COALESCE(m1.rank, '5000') AS 'm1rank',
COALESCE(m2.rank, '5000') AS 'm2rank'
答案 2 :(得分:0)
如果null排名将它们排在最后,否则按排名排序。如下所示:
ORDER BY CASE WHEN m1rank IS NULL OR m2rank IS NULL THEN 1 ELSE 0 END,
m1rank,
m2rank