我有这个查询,它与最后强加的单一限制一起使用。
select distinct
loc.mID,
loc.city,
loc.state,
loc.zip,
loc.country,
loc.latitude,
loc.longitude,
baseInfo.firstname,
baseInfo.lastname,
baseInfo.profileimg,
baseInfo.facebookID,
(((acos(sin(('37.816876'*pi()/180)) * sin((`latitude`*pi()/180))+cos(('37.816876'*pi()/180)) * cos((`latitude`*pi()/180)) * cos((('-121.285410' - `longitude`)*pi()/180))))*180/pi())*60*1.1515) AS `distance`,
teams.teamName,
teams.leagueType,
teams.teamType,
teams.subcat
FROM memb_geo_locations loc
left join memb_friends friends on (friends.mID = loc.mID or friends.friendID = loc.mID) and (friends.mID = '100018' or friends.friendID = '100018')
join memb_baseInfo baseInfo on baseInfo.mID = loc.mID
join memb_teams teams on teams.mID = loc.mID
where
loc.primaryAddress = '1'
and ((friends.mID is null or friends.friendID is null)
or (friends.isactive = 2))
and (
teams.teamName like '%Anaheim Ducks%'
or teams.teamName like '%San Jose Sharks%'
or teams.teamName like '%New England Patriots%'
or teams.teamName like '%New York Yankees%'
or teams.teamName like '%Orlando Magic%'
)
and loc.mID != 100018
having `distance` < 50
order by baseInfo.firstname
asc limit 30
但是我希望我的结果受到teamName的限制,每次最多3个结果,而且我已经尝试过的东西
select distinct
loc.mID,
loc.city,
loc.state,
loc.zip,
loc.country,
loc.latitude,
loc.longitude,
baseInfo.firstname,
baseInfo.lastname,
baseInfo.profileimg,
baseInfo.facebookID,
(((acos(sin(('37.816876'*pi()/180)) * sin((`latitude`*pi()/180))+cos(('37.816876'*pi()/180)) * cos((`latitude`*pi()/180)) * cos((('-121.285410' - `longitude`)*pi()/180))))*180/pi())*60*1.1515) AS `distance`,
teams.teamName,
teams.leagueType,
teams.teamType,
teams.subcat
FROM memb_geo_locations loc
left join memb_friends friends on (friends.mID = loc.mID or friends.friendID = loc.mID) and (friends.mID = '100018' or friends.friendID = '100018')
join memb_baseInfo baseInfo on baseInfo.mID = loc.mID
join memb_teams teams on teams.mID = loc.mID
where
loc.primaryAddress = '1'
and ((friends.mID is null or friends.friendID is null)
or (friends.isactive = 2))
and (
(select * from memb_teams where teamName like '%Buffalo Bills%' limit 2),
(select * from memb_teams where teamName like '%San Jose Sharks%' limit 2),
(select * from memb_teams where teamName like '%New England Patriots%' limit 2)
)
and loc.mID != 100018
having `distance` < 150
order by baseInfo.firstname
asc limit 30
没有成功,通常只是语法错误..或Operand Should 1 Column(s)
所以我希望有人可以让我知道如何优化我的查询,所以我可以将结果限制为每个teamName 3。而不是交错的结果,我可以有另外两个中的一个和另外两个中的20个和1和1(这是不希望的)。每个团队需要3个或更少,只是不知道如何。想法,不涉及从查询中处理大量数据集并通过服务器端代码循环它以输出我想要的结果?
答案 0 :(得分:0)
在MSSQL中我使用ROW_NUMBER函数,它将是这样的:
SELECT * FROM dbo.MyTable WHERE recno IN(SELECT recno FROM(SELECT Teamname,ROW_NUMBER()OVER(PARTITION BY Teamname ORDER BY recno DESC)AS intRow FROM dbo.MyTable)AS T WHERE intRow IN(1,2,3))
recno =您的唯一记录编号
基本上,您的子查询选择前3条记录,添加新的“行号”列。 Top Query选择Rownumber在1到3之间的所有记录。
我知道MYSQL中没有ROW_NUMBER()本机函数,所以你可以改用它: