使用python和postgresql从数据库记录中返回元组列表

时间:2016-04-03 00:03:03

标签: python database postgresql tuples

您好我正在努力完成此功能,我必须:

"""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
"""

目前我有这个功能试图解决这个问题:

def playerStandings():
    conn = connect()
    c = conn.cursor()
    c.execute("SELECT id, name \
            FROM players LEFT JOIN matches \
            ON players.id = matches.id_winner \
            ORDER BY players.id")
    result = c.fetchall()
    conn.close()
    return result

当我运行代码时,我收到此错误消息:

  

追踪(最近一次调用最后一次):文件“tournament_test.py”,行   152,在       testStandingsBeforeMatches()文件“tournament_test.py”,第61行,在testStandingsBeforeMatches中       提高ValueError(“每个playerStandings行应该有四列。”)ValueError:每个playerStandings行应该有四个   列。

tournament_test.py中的第152行是:

testStandingsBeforeMatches()

和第61行是:

if len(standings[0]) != 4:
    raise ValueError("Each playerStandings row should have four columns.")
[(id1, name1, wins1, matches1), (id2, name2, wins2, matches2)] = standings

最后变量“standings”是第54行中对我的函数playerStandings()的调用

standings = playerStandings()

这是我的sql脚本来创建数据库和表:

CREATE DATABASE tournament;
\c tournament;
CREATE TABLE players (id SERIAL, name TEXT, PRIMARY KEY (id)); 
CREATE TABLE matches (
    id_match SERIAL, 
    id_winner SERIAL REFERENCES players(id),
    id_looser SERIAL REFERENCES players(id),
    PRIMARY KEY (id_match)
);

我该怎么做才能解决这个问题?我是python的新手,所以我不太了解它

1 个答案:

答案 0 :(得分:0)

我不使用postgresql,代码可能不会直接在您的例程中使用,因此您需要在此基础上进行修改以使其正常工作。我只是给你一些提示,让你知道如何解决这个问题。

def playerStandings():
     conn = connect()
    c = conn.cursor()
    c.execute("SELECT id, name \
            FROM players LEFT JOIN matches \
            ON players.id = matches.id_winner \
            ORDER BY players.id")
    result = c.fetchall()#get all id and name, I don't know the type of result, assume its a list of dicts.

    for row in result:
        #sql to get wins
        c.execute("SELECT COUNT(*) AS wins FROM WHERE id_winner = row['id']");
        win_data = c.fetch()
        row['wins'] = win_data['wins']
        #sql to get matches
        c.execute("SELECT COUNT(*) AS matches FROM WHERE id_winner = row['id']" OR id_looser = row['id'])
        match_data = c.fetch()
        row['matches'] = match_data['matches']

    conn.close()
    return result