我有一个名为RESULTS的表,结构如下:
resultid,胜利者,类型
这个名为TICKETS的表格具有以下结构:
resultid,ticketid,赌注,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
答案 0 :(得分: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语法,更喜欢明确如何将表连接/链接在一起。
答案 1 :(得分: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
。