我在postgresql中加入一个表和多个子查询。
在其中一个第一个连接中,我正在加入一个表,其中包含一个玩家ID和名称列表,用于选择相关胜利的子查询。然而,有些球员尚未获胜。
以下是查询和输出:
select players.player_id, players.name, b.wins
from players
left join
(select winner, count(winner) as wins from outcomes group by winner) b
on players.player_id = b.winner;
player_id | name | wins
-----------+-------------------+------
500 | person 1 | 3
501 | person 2 |
502 | person 3 | 1
我想知道如果该列中的值为null,我将如何自动将此查询默认为获胜为0。我希望上表看起来像这样:
player_id | name | wins
-----------+-------------------+------
500 | person 1 | 3
501 | person 2 | 0
502 | person 3 | 1
答案 0 :(得分:0)
您使用coalesce()
:
select p.player_id, p.name, coalesce(w.wins , 0) as wins
from players p left join
(select winner, count(winner) as wins
from outcomes
group by winner
) w
on p.player_id = w.winner;
这是ANSI标准SQL,适用于大多数数据库,包括MySQL和Postgres。