2013-07-16 65 views
0

由於某些原因,我在DISTANCE區域中使用group by子句時得到了不同的結果。當我使用GROUP BY我能夠正確地鞏固我所有的電纜數量,但隨後的距離似乎比如果我不使用GROUP BY子句不同...SQL'Group By'子句更改數組結果

GROUP:

SELECT cable_no, 
     3959.0 * 5280.0 * acos(sin(radians($lat)) * sin(radians(mh_lat_a)) 
     + cos(radians($lat)) * cos(radians(mh_lat_a)) 
     * cos(radians(mh_long_a) - radians($lon))) as distance 
FROM extraction_worksheet 
WHERE mh_lat_a != '' 
GROUP BY cable_no 
HAVING distance <= $radius 

[{"cable_no":"90017","distance":"1604.6550964957787"},{"cable_no":"90018","distance":"41.09618442526487"}] 

Regular

SELECT cable_no, section_no, 
     3959.0 * 5280.0 * acos(sin(radians($lat)) * sin(radians(mh_lat_a)) 
     + cos(radians($lat)) * cos(radians(mh_lat_a)) 
     * cos(radians(mh_long_a) - radians($lon))) as distance 
FROM extraction_worksheet 
WHERE mh_lat_a != '' 
HAVING distance <= $radius 

[{"cable_no":"80010","section_no":"9","distance":"1398.9443263587134"},{"cable_no":"80010","section_no":"8","distance":"1669.0854859250592"},{"cable_no":"90017","section_no":"1","distance":"1604.6550964957787"},{"cable_no":"80010","section_no":"7","distance":"1831.1275113138754"},{"cable_no":"80010","section_no":"10","distance":"917.955911900792"},{"cable_no":"80017","section_no":"7","distance":"1788.0906282411715"},{"cable_no":"80017","section_no":"8","distance":"1685.9977194337882"},{"cable_no":"80017","section_no":"9","distance":"1544.2115596354815"},{"cable_no":"80017","section_no":"10","distance":"869.511708783779"},{"cable_no":"80010","section_no":"11","distance":"479.2133866402672"},{"cable_no":"80017","section_no":"11","distance":"428.6618645292709"},{"cable_no":"90018","section_no":"1","distance":"41.09618442526487"}] 
+1

爲什麼你總是使用'group by'?你沒有使用任何聚合函數 –

+0

我最初是這麼做的,因爲當我只想在下拉列表中顯示一個電纜數字時,我的下拉菜單會多次填充相同的數字。該集團看似固定它。 – jflay

+0

因爲不同的部分有不同的距離?嘗試在選擇列表/組中添加'section_no',或選擇你想要的(或某物) - 當同一電纜的多個部分位於半徑範圍內時(如數據所示),您希望發生什麼。 –

回答

1

Group By子句將匹配的行整合到一行中。因此,當你在cable_no上分組時,你會得到兩排,因爲你有兩個唯一的cable_no(80010和90017)。

如果您想要消除重複項,則應該使用您要過濾重複項的字段上的唯一子句。