0

我有一个名为 RESULTS 的表,其结构如下:

结果,获胜者,类型

还有一个名为 TICKETS 的表,其结构如下:

resultid,ticketid,bet,sum_won,状态

我想显示表 RESULTS 中的每一行,对于每个结果,我想使用表 TICKETS 中的值计算 totalBet 和 Sum_won

我试图进行一些连接,一些总和,但我无法得到我想要的。

SELECT *,COALESCE(SUM(tickets.bet),0) AS totalbets,
      COALESCE(SUM(tickets.sum_won),0) AS totalwins 
FROM `results` NATURAL JOIN `tickets` 
WHERE tickets.status<>0 
GROUP BY resultid

请给我一些建议。

我想显示这样的东西

RESULT WINNER TOTALBETS TOTALWINS
1       2        431       222
2       3         0         0
3       1         23        0
4       1         324       111
4

2 回答 2

1

采用:

   SELECT r.*,
          COALESCE(x.totalbet, 0) AS totalbet,
          COALESCE(x.totalwins, 0) AS totalwins
     FROM RESULTS r
LEFT JOIN (SELECT t.resultid,
                  SUM(t.bet) AS totalbet,
                  SUM(t.sum_won) AS totalwins
             FROM TICKETS t
            WHERE t.status != 0
         GROUP BY t.resultid) x ON x.resultid = r.resultid

我不关心 NATURAL JOIN 语法,更愿意明确说明如何将表连接/链接在一起。

于 2010-09-25T19:14:20.617 回答
0
SELECT *, COALESCE(SUM(tickets.bet),0) AS totalbets,
      COALESCE(SUM(tickets.sum_won),0) AS totalwins 
FROM `results` NATURAL JOIN `tickets` 
WHERE tickets.status<>0 
GROUP BY resultid

尝试将第一个替换*resultid. 如果这有帮助,那么添加更多列SELECT并同时添加它们GROUP BY

于 2010-09-25T19:17:46.677 回答