我有2张桌子PLAYER和MATCHES
CREATE TABLE PLAYER
(
id int PRIMARY KEY,
name varchar(255),
salary int
);
INSERT INTO PLAYER values(1,'MOHIT',1000);
INSERT INTO PLAYER values(2,'MNOP',2000);
INSERT INTO PLAYER values(3,'ABC',100);
INSERT INTO PLAYER values(4,'XYZ',10);
CREATE TABLE MATCHES
(
id int,
player_id int,
scores int
);
INSERT INTO MATCHES values(1,1,100);
INSERT INTO MATCHES values(2,2,52);
INSERT INTO MATCHES values(3,3,10);
INSERT INTO MATCHES values(4,1,200);
INSERT INTO MATCHES values(5,1,300);
谁能告诉我MYSQL查询来找到MOHIT打进双世纪比赛(200次)的比赛次数。
我使用了以下查询,但给了我SQL错误。
查询:-
SELECT FIND_IN_SET(Select m.id from MATCHES m
JOIN PLAYER p
on p.id=m.player_id
WHERE p.name='MOHIT'
AND m.scores>=200
ORDER BY m.scores limit 1,(SELECT GROUP_CONCAT(
SELECT m.id from MATCHES m
JOIN PLAYER p
on p.id=m.player_id
WHERE p.name='MOHIT'
))) AS RANK;
在此查询中,我试图找到MOHIT为其赢得双世纪的第一个match_id,然后在他参加的所有比赛中找到该match_id的排名。
由于MOHIT玩了2场游戏得分200或超过200,则预期输出应为2。
我们将不胜感激任何帮助。
答案 0 :(得分:0)
如果我的理解正确,则可以使用MYSQL COUNT()达到要求
SELECT COUNT(*) AS no_of_match
FROM matches m
JOIN player p
ON p.id = m.player_id
WHERE p.NAME = 'MOHIT'
AND m.scores >= 200;
答案 1 :(得分:0)
用例何时
SELECT p.name ,sum(case when scores>=200 then 1 else 0 end) AS no_of_match_200
FROM matches m
JOIN player p
ON p.id = m.player_id
where p.name ='MOHIT'
group by p.name
http://sqlfiddle.com/#!9/1762cb/7
name no_of_match_200
MOHIT 2
答案 2 :(得分:0)
在此解决方案中,内部查询会计算出累积得分和所打比赛的计数,外部查询会找到累积得分符合您的边界条件的最早比赛。
select p.name,min(s.matchesplayed) matchesplayed
from player p
join
(
select m.player_id,
(select sum(m1.scores) from matches m1 where m1.player_id = m.player_id and m1.id <= m.id) sumscore,
(select count(m1.scores) from matches m1 where m1.player_id = m.player_id and m1.id <= m.id) matchesplayed
from matches m
) s on s.player_id = p.id
where # p.name = 'mohit' and
sumscore>= 200
group by p.name;
在这种情况下,我的查询将找到任何玩家。
答案 3 :(得分:0)
我会这样:
select count(*)
from players p join
matches m
on p.id = m.player_id
where p.name = 'Mohit' and
m.id < (select min(m2.id)
from matches m2
where m2.player_id = m.player_id and
m2.score >= 200
);