2017-06-01 119 views
0

所以我有這個疑問:SQL - 查詢返回重複的記錄,即使GROUP BY

SELECT P.*, 
    (3959 * acos(cos(radians('37.785834')) 
    * cos(radians(CA.lat)) 
    * cos(radians(CA.lng) 
    - radians('-122.406417')) 
    + sin(radians('37.785834')) 
    * sin(radians(CA.lat)))) AS distance 
FROM adp2_posts as P 
JOIN adp2_offer_details C ON C.merchant_id = P.ID 
JOIN adp2_addresses CA ON CA.address_id = C.address_id 
WHERE P.post_type = 'merchant' 
    AND P.post_status = 'publish' 
    AND CA.mm = "dallasftworth" 
    AND C.cats RLIKE CONCAT("[[:<:]]", REPLACE(199, ",", "[[:>:]]|[[:<:]]"), "[[:>:]]") 
GROUP BY CA.address_id, P.ID 
HAVING (distance < 999999999999999999 AND P.coupon_count > 0) ORDER BY distance ASC LIMIT 0 , 20 

我希望它從返回左表的獨特價值,但它也返回重複。

結果:

the results

我有點被這個困惑。

+5

如果您按A,B分組,您會得到一行A,B的唯一組合 –

+0

您在查詢中有'SELECT P. *',表示列中的列數多於圖像中的列數。這可能很容易表明在MySQL中對「GROUP BY」的誤用/誤解。請從您的查詢中發佈更完整的結果集,並查看您希望查看結果的示例。不要將它們作爲圖像發佈,像表格一樣將它們複製/粘貼到代碼編輯器中,突出顯示和'ctl-k'或使用'{}'按鈕就像代碼塊一樣。 –

+0

有時候看到MySQL不會爲這種查詢拋出錯誤是非常令人沮喪的。 – Utsav

回答

0

對不起,沒有提供完整的背景,它是一個漫長的一天,但我終於明白了。

這裏結束查詢:

SELECT P.*, MIN((3959 * acos(cos(radians('37.785834')) * cos(radians(CA.lat)) * cos(radians(CA.lng) - radians('-122.406417')) + sin(radians('37.785834')) * sin(radians(CA.lat))))) AS distance FROM adp2_posts as P JOIN adp2_offer_details C ON C.merchant_id = P.ID JOIN adp2_addresses CA ON CA.address_id = C.address_id WHERE P.post_type = 'merchant' AND P.post_status = 'publish' AND CA.mm = "dallasftworth" AND C.cats RLIKE CONCAT("[[:<:]]", REPLACE(199, ",", "[[:>:]]|[[:<:]]"), "[[:>:]]") GROUP BY P.ID HAVING (distance < 999999999999999999 AND P.coupon_count > 0) ORDER BY distance ASC LIMIT 0 , 20 

的問題是,CA.address_id地方不同,GROUP BY把它作爲唯一的值。我所做的只是選擇最小距離的P.*(這正是我的業務邏輯所要求的)。