在第二次调用我的函数后,我得到了以下错误:作为表达式使用的子查询返回了多行

2024-04-19 02:17:59 发布

您现在位置:Python中文网/ 问答频道 /正文

这是my playerStandings()函数的定义:

def playerStandings():
    """Returns a list of the players and their win records, sorted by wins.

    The first entry in the list should be the player in first place, or a player
    tied for first place if there is currently a tie.

    Returns:
      A list of tuples, each of which contains (id, name, wins, matches):
        id: the player's unique id (assigned by the database)
        name: the player's full name (as registered)
        wins: the number of matches the player has won
        matches: the number of matches the player has played
    """
    db = connect()
    c = db.cursor()
    c.execute("select players.id,players.name, count((select matches.winner from matches where matches.winner = players.id))as win, count((matches.winner))as matches from players left join matches on players.id = matches.winner or players.id = matches.loser group by players.id order by win desc,id")
    standing = c.fetchall()
    db.close()
    return standing

当我第一次调用这个函数时,程序运行正常,问题是当我第二次尝试打印我的排名时。以下是我的主要功能

standings = playerStandings()
print playerStandings()
[id1,id2,id3,id4,id5,id6] = [row[0] for row in standings]
reportMatch(id2,id1)
reportMatch(id4,id3)
reportMatch(id5,id6)
print playerStandings()
print swissPairings()
reportMatch(id2,id4)
reportMatch(id1,id5)
reportMatch(id6,id3)
print playerStandings()
print swissPairings()

Tags: ofthenameidbywinlistplayer
1条回答
网友
1楼 · 发布于 2024-04-19 02:17:59

不要把SELECT放在COUNT()里面。使用SUM()对符合其他条件的行进行计数

SELECT p.id, p.name, SUM(CASE WHEN m.winner = p.id THEN 1 ELSE 0 END) AS win, COUNT(m.winner) AS matches
FROM players as p
LEFT JOIN matches AS m ON p.id IN (m.winner, m.loser)
GROUP BY p.id
ORDER BY win DESC, p.id

相关问题 更多 >