使用列

时间:2016-09-15 08:14:23

标签: mysql sql database

这是我的SQL查询:

SELECT 
       asi.nid_lot AS nid_lot,
       asi.nid_programme AS nid_programme,
       asi.mensualite_habiter_3p AS mensualite_habiter_3p,
      ( 
       6371 * acos( 
              cos(radians(45.8219562)) 
              * cos(radians(lat)) 
              * cos(radians(lng) - radians(4.9013965)) 
              + sin(radians(45.8219562)) 
              * sin(radians(lat)) 
                  ) 
       ) AS distance 

FROM search_index asi 

WHERE 
     (mensualite_habiter_3p < 875.56) 
     AND (mensualite_habiter_3p > 619.5) 
     ORDER BY distance ASC, mensualite_habiter_3p ASC 

我的结果是:

enter image description here

如何通过&nbsp_programme&#39;只获得一个结果? ?事实上,搜索的目标是得到这个结果:

 nid_lot    nid_programme   mensualite_habiter_3p   distance    
 1858       1805            676.41                  0.00013425878593145295
 1846       1804            683.44                  10.090534238610191
 1887       1808            794.4                   14.146197138015372
 1816       1792            700.7                   36.64897301190563
 1912       1811            774.58                  97.35583327362087
 1875       1807            870.43                  100.34682452197465

正如您所看到的,只有一次'nid_programme&#39; (第一个)

3 个答案:

答案 0 :(得分:0)

尝试name123

group by

答案 1 :(得分:0)

如果你想为每个nid_programme只获得一行,请尝试这个,我认为nid_lot持有唯一数据,所以基于max或min nid_id你可以拍摄那一行,但正如你所说的基于最低的mensualite_habiter_3p,你可以尝试以下。

---基于mensualite_habiter_3p的最小值

SELECT 
    a.nid_lot, 
    a.nid_programme, 
    a.mensualite_habiter_3p, 
    a.distance
FROM tmptest a  
INNER JOIN (SELECT b.nid_programme, MIN(b.mensualite_habiter_3p) tot 
             FROM tmptest b 
            GROUP BY b.nid_programme) t ON t.tot = a.mensualite_habiter_3p
AND a.nid_programme = t.nid_programme

答案 2 :(得分:0)

根据您发布的所需结果,您似乎想要按[nid_programme]进行分组,并将min用于其余列:

SELECT 
       MIN(asi.nid_lot) AS nid_lot,
       asi.nid_programme AS nid_programme,
       MIN(asi.mensualite_habiter_3p) AS mensualite_habiter_3p,
      MIN(( 
       6371 * acos( 
              cos(radians(45.8219562)) 
              * cos(radians(lat)) 
              * cos(radians(lng) - radians(4.9013965)) 
              + sin(radians(45.8219562)) 
              * sin(radians(lat)) 
                  ) 
       )) AS distance 

FROM search_index asi 
WHERE 
     (mensualite_habiter_3p < 875.56) 
     AND (mensualite_habiter_3p > 619.5) 
GROUP BY asi.nid_programme
ORDER BY MIN(( 
       6371 * acos( 
              cos(radians(45.8219562)) 
              * cos(radians(lat)) 
              * cos(radians(lng) - radians(4.9013965)) 
              + sin(radians(45.8219562)) 
              * sin(radians(lat)) 
                  ) 
       )) ASC, MIN(asi.mensualite_habiter_3p) ASC