Mysql查询没有按顺序分组

时间:2014-07-21 21:42:08

标签: php mysql

不确定此信息是否足够。 我有几个表,我正在运行此查询,它返回给我以下结果。

SELECT   CONCAT(pm.fname, " " ,pm.lname) AS fullname,cl.id as clubid,pm.id as player_id,

    ( 3959 * acos( cos( radians(50.82) ) * cos( radians( cm.lat ) )
     * cos( radians( -0.373 ) - radians(-0.373) ) + sin( radians(50.82) )
     * sin( radians( cm.lat ) ) ) ) AS distance

FROM clubmapper AS cm

LEFT OUTER JOIN clubs AS cl ON cl.id = cm.club_id

INNER JOIN playermaster AS pm ON pm.id = cm.usertype_id

LEFT JOIN countries AS co ON co.country_code = pm.nationality

WHERE (pm.fname LIKE 'josephthirtye%' OR pm.lname LIKE 'josephthirtye%')   

#group by cm.usertype_id

ORDER BY distance  ASC,pm.fname ASC, pm.lname ASC
LIMIT 0,12

此查询返回下表:

enter image description here

但我只希望距离最小的第一个结果。我尝试使用group by(在查询中注释),但那给了我最后一行。我只想要那个player_id的第一行

和建议?

以下是与漂亮字体相同的查询:

enter image description here

更多数据: enter image description here

我想要距离最小的唯一player_id

2 个答案:

答案 0 :(得分:0)

这是我解决它的方式。谢谢大家的建议。

SELECT   CONCAT(pm.fname, " " ,pm.lname) AS fullname,cl.id as clubid,pm.id as player_id    

FROM (SELECT ( 3959 * acos( cos( radians(50.82) ) * cos( radians( lat ) )
     * cos( radians( -0.373 ) - radians(-0.373) ) + sin( radians(50.82) )
     * sin( radians( lat ) ) ) ) AS distance FROM clubmapper) AS cm

LEFT OUTER JOIN clubs AS cl ON cl.id = cm.club_id

INNER JOIN playermaster AS pm ON pm.id = cm.usertype_id

LEFT JOIN countries AS co ON co.country_code = pm.nationality

WHERE (pm.fname LIKE 'josephthirtye%' OR pm.lname LIKE 'josephthirtye%')   

group by pm.id

ORDER BY distance  ASC,pm.fname ASC, pm.lname ASC

LIMIT 0,12

答案 1 :(得分:0)

  

但我只希望第一个结果是距离是min

此查询将为您提供距离最短的结果

SELECT 
    CONCAT(pm.fname, ' ', pm.lname) AS fullname,
    cl.id as clubid,
    pm.id as player_id,
    MIN(3959 * acos(cos(radians(50.82)) * cos(radians(cm.lat)) * cos(radians(- 0.373) - radians(- 0.373)) + sin(radians(50.82)) * sin(radians(cm.lat)))) AS Distance
FROM
    clubmapper AS cm
        LEFT OUTER JOIN
    clubs AS cl ON cl.id = cm.club_id
        INNER JOIN
    playermaster AS pm ON pm.id = cm.usertype_id
        LEFT JOIN
    countries AS co ON co.country_code = pm.nationality
WHERE
    (pm.fname LIKE 'josephthirtye%'
        OR pm.lname LIKE 'josephthirtye%');

我不知道这是否是您想要的,但部分问题似乎只有一个结果。