MySql限制每个分组在具有多个连接的查询中的结果

时间:2013-03-26 05:17:50

标签: php mysql

我有这个查询

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.8068406'*pi()/180)) * sin((`latitude`*pi()/180))+cos(('37.8068406'*pi()/180)) * cos((`latitude`*pi()/180)) * cos((('-121.3062367' - `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 = '100019' or friends.friendID = '100019') 
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 '%Buffalo Bills%' or teams.teamName like '%New England Patriots%' or teams.teamName like '%Dallas Cowboys%')
and 
    loc.mID != 100019 
having 
    `distance` < 50 
order by baseInfo.firstname asc limit 30

这完全符合我的核心需求。但是,我试图确定如何进行查询并对其进行优化,以便

部分
(teams.teamName like '%Buffalo Bills%' or teams.teamName like '%New England Patriots%' or teams.teamName like '%Dallas Cowboys%')

每个队列名称都会产生最大定义的结果数量(每次最少或没有,只需寻求最大值),同时在查询结束时指定限制的最大输出。无论如何我可以改进这个查询来做我希望的事情吗?有人告诉我在最近的另一篇与此类似的帖子中我查看UNION,但我不确定这将如何适用于此查询?假设这是正确的方向。

0 个答案:

没有答案