2013-01-23 98 views
1

我正在構建一個在附近位置查找物品的購物系統。基本上,每個位置(供應商)在稱爲位置的表中具有條目,具有名稱,緯度,經度和其他的列...然後是項目表,其中具有標識該項目屬於哪個位置的外鍵至。SQL:限制和隨機結果加入

基本上,我想找出所有用戶附近的物品:我可以用下面的查詢做:

但是我想做到以下幾點 - 選擇從該位置隨機 項目 - 限制從每個位置的項目數量只有幾個(比如說5) - 隨機化所有結果,以便它們不按位置分組

這是迄今爲止我所做的必須困難的查詢,即時變得更好但是所以堅持這一個 - 任何幫助,如果非常感謝!謝謝!!

這是到目前爲止我的select語句:

SELECT Location.idLocation 
, Location.locationName 
, Location.tagline 
, Location.tags 
, Location.shortAddress 
, (3959 * acos(cos(radians('40.181')) * cos(radians(Location.latitude)) * cos(radians(Location.longitude) - radians('-74.0265')) + sin(radians('40.181')) * sin(radians(Location.latitude)))) AS distance 
, Item.idItem 
, Item.dateAdded 
, Item.fidLocation 
, Item.itemName 
, Item.description 
, Item.fullImageName 
, Item.thumbnailImageName 
FROM 
    Location 
INNER JOIN Item 
ON Location.idLocation = Item.fidLocation 
HAVING distance < '1000' 
+0

'爲了通過蘭特()限制5'是快速/髒/廉價/昂貴方法。 –

+0

是否要隨機從每個位置選擇5個項目,然後如何訂購它們? –

+0

謝謝。是每個地點最多5件物品,而不是總共5件物品。 – dbrateris

回答

0

OK.Here是基於假設未經檢驗的版本。

SELECT 
    Location.idLocation, 
    Location.locationName, 
    Location.tagline, 
    Location.tags, 
    Location.shortAddress, 
    (3959 * acos(cos(radians('40.181')) * cos(radians(Location.latitude)) * cos(radians(Location.longitude) - radians('-74.0265')) + sin(radians('40.181')) * sin(radians(Location.latitude)))) AS distance, 
    Item.idItem, 
    Item.dateAdded, 
    Item.fidLocation, 
    Item.itemName, 
    Item.description, 
    Item.fullImageName, 
    Item.thumbnailImageName 
FROM Location 
    INNER JOIN (select * 
      from Item 
      order by RAND() 
      limit 5) as Item 
    ON Location.idLocation = Item.fidLocation 
ORDER BY RAND() 
HAVING distance < '1000' 
+0

這將只選擇5個總項目,而不是每個位置5個項目。然後它會過濾掉超過1000英里(或公里,我不確定)的任何東西,所以你可能什麼也得不到。 – Barmar

+0

刪除限制五是什麼結果? –

+0

然後你會得到一切,就像問題中的查詢一樣。 – Barmar

0
SET @local = 0; 
SET @group = 0; 

SELECT Location.idLocation 
, Location.locationName 
, Location.tagline 
, Location.tags 
, Location.shortAddress 
, (3959 * acos(cos(radians('40.181')) * cos(radians(Location.latitude)) * cos(radians(Location.longitude) - radians('-74.0265')) + sin(radians('40.181')) * sin(radians(Location.latitude)))) AS distance 
, Item.idItem 
, Item.dateAdded 
, Item.fidLocation 
, Item.itemName 
, Item.description 
, Item.fullImageName 
, Item.thumbnailImageName 
, @level := IF(@group = idLocation, @level+1, 1) AS level 
, @group := idLocation as tempGroup 
FROM 
    Location 
INNER JOIN Item 
ON Location.idLocation = Item.fidLocation 
order by idLocation, RAND(), 
HAVING distance < '1000' AND level <= 5 
+0

謝謝Barmar,這是一種工作。什麼是@運算符叫,所以我可以查看並瞭解它 – dbrateris

+0

'@'不是一個運算符,它是用戶定義的變量所需的前綴。 http://dev.mysql.com/doc/refman/5.6/en/user-variables.html – Barmar