我有三个表来维护MySQL的投注系统。我们的用户说,即使获胜,某些投注单也不会改变“获胜状态”。因此,我正在寻找这些错误的结果。很快,我需要来自betslips表的ID,该ID具有来自betslips_inner表的匹配选项(所有应该匹配)以及来自于bets表的投注结果。
SELECT a.ID,a.betslip,a.bet,a.choice,c.result
FROM betslips_inner a JOIN
betslips b JOIN
bets c
ON b.won=0 AND a.betslip=b.ID AND c.ID=a.bet AND a.choice=c.result
GROUP BY a.betslip
having count(*) = (SELECT COUNT(*) FROM betslips_inner WHERE betslip = a.betslip)
此查询为我提供了一些结果。但是,似乎只给了我所需的实际结果的一小部分。
我在这里想念什么?为什么此查询会导致我得到真实结果,但不是所有真实结果?
示例数据
BET
-------
ID result
1 1
2 2
3 1
4 1
-------
BETSLIPS
-------
ID won
1 0
2 0
-------
BETSLIPS_INNER
-------
ID betslip bet choice
1 1 1 1
2 1 2 2
3 1 3 1
4 2 4 2
5 2 3 1
-------
因此,预期的投注单应为ID:1的投注单。第二个投注单内有一场胜利比赛,但没有“全场比赛”。
例如,下面的查询;
SELECT a.bet as bet, a.choice as choice, b.result as result, c.ID as ID,
c.won as won
FROM betslips_inner a
JOIN bet b JOIN betslips c ON
b.ID=a.bet AND c.ID=a.betslip
WHERE a.betslip = 5128919
给我这个,
bet choice result ID won
66897 2 2 5128919 0
66895 1 1 5128919 0
66695 2 2 5128919 0
38196 2 2 5128919 0
66995 2 2 5128919 0
66686 1 1 5128919 0
66715 1 1 5128919 0
但是在第一个查询中找不到ID 5128919的投注单。 (我应该是因为这是赢率为= 0的全场比赛投注单)
答案 0 :(得分:1)
我有一种直觉,您正在寻找类似下面的SQL之类的东西。
哪个在下注上使用LEFT JOIN。
在BETSLIPS_INNER和BETS表之间,HAVING限制为相同的结果。
SELECT slipin.betslip,
COUNT(slipin.ID) as total_inner,
COUNT(bet.ID) as total_bet_matching
FROM BETSLIPS_INNER slipin
JOIN BETSLIPS slip ON (slip.ID = slipin.betslip)
LEFT JOIN BETS bet ON (bet.ID = slipin.bet AND bet.result = slipin.choice)
WHERE slip.won = 0
GROUP BY slipin.betslip
HAVING COUNT(slipin.ID) = COUNT(bet.ID);
基于示例数据,它将返回betslip1。
但不是betslip 2。
以下是示例数据:
create table BETS (ID int, result int);
create table BETSLIPS (ID int, won int);
create table BETSLIPS_INNER (ID int, betslip int, bet int, choice int);
insert into BETS (ID, result) values (1,1),(3,1),(4,1),(2,2);
insert into BETSLIPS (ID, won) values (1,0),(2,0);
insert into BETSLIPS_INNER (ID, betslip, bet, choice) values
(1,1,1,1),(2,1,2,2),(3,1,3,1),
(4,2,4,2),(5,2,3,1);