MYSQL让那些观看了所有足球比赛的人

时间:2018-01-07 08:44:48

标签: mysql

 $ npm install --save pinkie-promise@2.0.2

离。

风扇:

fan(*IDfan*,name,surname)
match(*IDmatch*, type_of_competition, teamA, teamB, date, scoreA, scoreB)
booking(*IDfan,IDmatch*,price)...
 *name* : name is the primary key ` 

匹配

IDfan     Name   Surname
---------------------
1     | A      |A
2     | B      |B
3     | C      |C

预订:

IDmatch   type        teamA    teamB         date...
----------------------------------------------------
1     | champions |Juve     |Barcellona |01/10/17
2     | league    |Milan    |Real       |02/11/17
3     | TIM cup   |Inter    |Napoli     |03/12/17

早上好,我不知道如何选择观看所有比赛的球迷,考虑到球迷可以为一场比赛购买更多门票。例如,应用于上述数据库的脚本结果必须是:

IDfan名字姓氏

IDfan     IDmatch   price
---------------------
1     | 1      |5
1     | 2      |6
1     | 3      |7
2     |1       |8
2     |1       |8
2     |1       |8
3     |2       |5
3     |3       |10

1 个答案:

答案 0 :(得分:2)

<强>被修改

booking表中,相同值的行出现三次是奇怪的。

IDfan     IDmatch   price
---------------------
2     |1       |8
2     |1       |8
2     |1       |8

假设三次出现没错, 这将是正确答案(未经测试)。

SELECT fan.*
FROM (SELECT DISTINCT IDfan, IDmatch
    FROM booking) AS distinct_booking
JOIN fan ON distinct_booking.IDfan = fan.IDfan
GROUP BY fan.IDfan, fan.Name, fan.Surname
HAVING COUNT(*) = (SELECT COUNT(*) FROM match)
;

另一方面,假设booking表具有IDfanIDmatch的唯一约束,三次出现是错误的, 试试这个。测试和工作

SELECT fan.*
FROM booking
JOIN fan ON booking.IDfan = fan.IDfan
GROUP BY fan.IDfan, fan.Name, fan.Surname
HAVING COUNT(*) = (SELECT COUNT(*) FROM match)
;

对于mysql,这也可以工作(测试)

SELECT fan.*
FROM booking
JOIN fan ON booking.IDfan = fan.IDfan
GROUP BY fan.IDfan
HAVING COUNT(*) = (SELECT COUNT(*) FROM match)
;

-

此评论的说明。

  

你能解释一下你为什么这样做:GROUP BY fan.IDfan,fan.Name,fan.Surname?

某些数据库有规则:SELECT中的列必须位于GROUP BY子句中。

要获得IDfan名字姓氏,我写了GROUP BY fan.IDfan, fan.Name, fan.Surname 但是mysql不是这种情况,如果主键在GROUP BY中,那就没关系。

所以,我再次阅读你的问题并且我意识到你使用了mysql,那么这也可以在mysql中使用。

SELECT fan.*
FROM booking
JOIN fan ON booking.IDfan = fan.IDfan
GROUP BY fan.IDfan
HAVING COUNT(*) = (SELECT COUNT(*) FROM match)
;