【发布时间】:2020-03-22 22:49:12
【问题描述】:
我有 3 张桌子。
第一个表是带有列的战斗:
--battleId(primary)--gameId(foreign)--prize--
第二张表是带有列的游戏:
--gameId(primary)--gameName--
第三张表是 BattleParticipants 列:
--battleParticipantsId(primary)--userId(foreign)--battleId(foreign)--score--
首先我编写了这个查询来加入战斗和游戏并获取battleId、prize和gameName数据:
SELECT
battles.battleId
, battles.prize
, games.gameName
FROM
battles
JOIN
games
ON
battles.gameId = games.gameId
此查询返回每个战斗的battleId,prize,gameName数据。
我想扩展这个查询以获得每场战斗的参与者数量(这意味着 BattleParticipant 表中的行,Battles.battleId = BattleParticipants.battleId ) 通过以某种方式将其与 BattleParticipants 表结合起来。
所以结果应该是: BattleId,奖品,游戏名称,Battle 参与者人数
示例表和结果:
战斗:
--battleId(primary)--gameId(foreign)--prize--
asd123 1 100
asd1234 2 200
asd1235 1 300
游戏:
--gameId(primary)--gameName--
1 Some Game
2 Another Game
战斗参与者:
--battleParticipantsId(primary)--userId(foreign)--battleId(foreign)--score--
1 qwedqweqw asd123 100
2 qweqwe asd1234 200
3 qweadgjhg asd123 400
4 asd asd123 500
预期结果:
[ RowDataPacket {
battleId: 'asd123',
prize: 100,
gameName: 'Some Game',
numberOfParticipantInBattle: 3 },
RowDataPacket {
battleId: 'asd1234',
prize: 200,
gameName: 'Some Game',
numberOfParticipantInBattle: 1 },
RowDataPacket {
battleId: 'asd1235',
prize: 300,
gameName: 'Some Game',
numberOfParticipantInBattle: 0 }
]
如果我尝试@Gordon Linoff 给出的答案,这就是我得到的结果:
[ RowDataPacket {
battleId: 'asd123',
prize: 100,
gameName: 'Some Game',
numberOfParticipantInBattle: 3 },
RowDataPacket {
battleId: 'asd1234',
prize: 200,
gameName: 'Some Game',
numberOfParticipantInBattle: 1 },
RowDataPacket {
battleId: 'asd1235',
prize: 300,
gameName: 'Some Game',
numberOfParticipantInBattle: 0 },
RowDataPacket {
battleId: 'asd123',
prize: 100,
gameName: 'Another Game',
numberOfParticipantInBattle: 3 },
RowDataPacket {
battleId: 'asd1234',
prize: 200,
gameName: 'Another Game',
numberOfParticipantInBattle: 1 },
RowDataPacket {
battleId: 'asd1235',
prize: 300,
gameName: 'Another Game',
numberOfParticipantInBattle: 0 } ]
有什么方法可以删除重复项还是我应该手动删除
【问题讨论】:
-
请使用示例数据和所需结果设置某种类型的数据库小提琴。