sqlite结合了来自不同表的2个查询以组成一个

时间:2019-02-25 05:52:39

标签: python-3.x sqlite

我最近再次使用sql,上次使用它是在Microsoft Access 2000中,所以如果我落后于时代,请忍受。

我的不和谐服务器上有2种无意义的虚拟货币供玩家玩无意义的游戏。这两种货币的交易当前都存储在单独的表中。

我希望对每个玩家的所有交易进行汇总,以便为每个货币提供一个当前金额。我个人可以这样做:

SELECT
 tblPlayers.PlayerID AS PlayerID,
 tblPlayers.Name AS Name,
 SUM(tblGorillaTears.Amount) 
FROM 
 tblPlayers 
INNER JOIN 
 tblGorillaTears
ON 
 tblPlayers.PlayerID = tblGorillaTears.PlayerID 
GROUP BY 
 tblPlayers.PlayerID;

SELECT
 tblPlayers.PlayerID AS PlayerID,
 tblPlayers.Name AS Name,
 SUM(tblKebabs.Amount) 
FROM 
 tblPlayers 
INNER JOIN 
 tblKebabs 
ON 
 tblPlayers.PlayerID = tblKebabs.PlayerID 
GROUP BY 
 tblPlayers.PlayerID;

我需要的是一张在一行上输出用户名ID和每种货币的总数的表,但是当我这样做时:

SELECT
 tblPlayers.PlayerID AS PlayerID,
 tblPlayers.Name AS Name,
 SUM(tblGorillaTears.Amount) AS GT,
 0 as Kebabs
FROM 
 tblPlayers 
INNER JOIN 
 tblGorillaTears
ON 
 tblPlayers.PlayerID = tblGorillaTears.PlayerID 
GROUP BY 
 tblPlayers.PlayerID
UNION 
SELECT
 tblPlayers.PlayerID AS PlayerID,
 tblPlayers.Name AS Name,
 0 as GP,
 SUM(tblKebabs.Amount) 
FROM 
 tblPlayers 
INNER JOIN 
 tblKebabs 
ON 
 tblPlayers.PlayerID = tblKebabs.PlayerID 
GROUP BY 
 tblPlayers.PlayerID;

对于每种货币,每个玩家的结果都排在一行。我如何才能使两种货币都出现在同一行?

以前,在MSAccess中,我能够创建两个查询,然后对这两个查询进行查询,就好像它们是一个表一样,但是在这种情况下,我不知道该怎么做。谢谢<3

1 个答案:

答案 0 :(得分:1)

UNION将确保添加新行,您可以尝试以下查询。

SELECT TP.playerid                        AS PlayerID, 
       TP.NAME                            AS NAME, 
       (SELECT Sum(TG.amount) 
        FROM   tblgorillatears TG 
        WHERE  TG.playerid = TP.playerid) AS GT, 
       (SELECT Sum(TG.amount) 
        FROM   tblkebabs TG 
        WHERE  TG.playerid = TP.playerid) AS Kebabs 
FROM   tblplayers TP