SQL显示最低值的DISTINCT行

时间:2016-07-26 17:33:16

标签: mysql sql database

我正在使用MySQL 5.5。我有一个SQL问题。

我有以下表格(oneToMany - 一个员工到多个地点):

+----------+   +-------------------+  +-----------+
| EMPLOYEE |   | EMPLOYEE_LOCATION |  | LOCATION  |
 ----------     -------------------    -----------
|ID        |   |EMP_ID             |  | ID        |
|          |   |LOC_ID             |  | LATITUDE  |
|          |   |                   |  | LONGITUDE |
+----------+   +-------------------+  +-----------+

数据:

+----+          +-------------+       +-------------------------------+
| ID |          |EMP_ID|LOC_ID|       |ID | LATITUDE    | LONGITUDE   |  
+----+          +-------------+       +-------------------------------+
| 1  |          |  1   |  1   |       | 1 | 28.80000000 |-25.76666700 |
| 2  |          |  1   |  2   |       | 2 | 27.35000000 |-25.76266700 |
| 3  |          |  1   |  3   |       | 3 | 27.95000000 |-25.66666700 |
+----+          |  2   |  4   |       | 4 | 26.85000000 |-25.76666700 |
                |  2   |  5   |       | 5 | 28.85000000 |-25.76666700 |
                |  4   |  6   |       | 6 | 28.85000000 |-25.86666701 |
                +-------------+       +-------------------------------+

我的SQL:

select e.ID,
( 6371 * acos( cos( radians(37) ) * cos( radians( o.LATITUDE) ) * cos( radians( o.LONGITUDE) - radians(-122) ) + sin( radians(37) ) * sin( radians( o.LATITUDE) ) ) ) AS distance
from
    www.employee as e
inner join
    www.employee_location as eo
        on e.id=eo.EMP_ID 
inner join
    www.location as o
        on eo.LOC_ID=o.ID        
order by distance

回归:

ID| DISTANCE
--+------------------
3 | 8622.766267835324
2 | 8630.684502219874
1 | 8633.923476508438
1 | 8697.058324230797
1 | 8728.471585032592
2 | 8760.772628068693

我正在尝试制定我的SQL,以便它只为每个EMPLOYEE(3行)返回一行。返回的每一行都是由DISTANCE排序的最低 DISTANCE值的行。

例如,我想要以下内容:

ID| DISTANCE
--+------------------
3 | 8622.766267835324
2 | 8630.684502219874
1 | 8633.923476508438

感谢任何帮助,谢谢。

2 个答案:

答案 0 :(得分:3)

不需要子查询。只需在你的查询中做一个小组,并在距离上做一分钟 -

select e.ID,
min(( 6371 * acos( cos( radians(37) ) * cos( radians( o.LATITUDE) ) * cos( radians( o.LONGITUDE) - radians(-122) ) + sin( radians(37) ) * sin( radians( o.LATITUDE) ) ) )) AS distance
from
    www.employee as e
inner join
    www.employee_location as eo
        on e.id=eo.EMP_ID 
inner join
    www.location as o
        on eo.LOC_ID=o.ID   
group by e.ID     
order by distance

答案 1 :(得分:1)

您可以使用外部查询并获得最小值

select ID, min(distance) as mindistance from (
select e.ID,
( 6371 * acos( cos( radians(37) ) * cos( radians( o.LATITUDE) ) * cos( radians( o.LONGITUDE) - radians(-122) ) + sin( radians(37) ) * sin( radians( o.LATITUDE) ) ) ) AS distance
from
    www.employee as e
inner join
    www.employee_location as eo
        on e.id=eo.EMP_ID 
inner join
    www.location as o
        on eo.LOC_ID=o.ID ) xxx
group by ID;