我一直在試圖弄清楚這幾個小時,似乎我卡住了。Mysql選擇每行5行(使用IN操作符)
當我想在下面的查詢中做的是,我將一些位置ID傳遞給IN
運算符,我不希望MySQL返回所有結果(表太大),但每個位置ID只有5項(如果項目存在)。
我暫時放了一個LIMIT 100
,直到我完成了你的幫助。
這裏的查詢:
$sql = "SELECT SQL_CACHE deals.deal_ID, deals.slug, deals.url, deals.previous_price, deals.title, deals.image, deals.price, deals.end, deals.purchases, deals.date_added,
deals_locations.location_ID, deals.hits
FROM deals
INNER JOIN deals_locations
WHERE deals.status = 'active'
AND deals_locations.deal_ID = deals.deal_ID
AND deals_locations.location_ID IN (".implode(', ', $location_IDs).")
GROUP BY deals.deal_ID
LIMIT 100;";
非常感謝您的寶貴時間。
編輯:現在我的查詢輸出如下:
SELECT SQL_CACHE deals.deal_ID
,deals.slug
,deals.url
,deals.previous_price
,deals.title
,deals.image
,deals.price
,deals.end
,deals.purchases
,deals.date_added
,deals_locations.location_ID
,deals.hits
FROM deals
INNER JOIN deals_locations
WHERE deals.status = 'active'
AND (
SELECT COUNT(*) FROM deals
WHERE deals.deal_ID = deals_locations.deal_ID
) <= 5
AND deals_locations.deal_ID = deals.deal_ID
AND deals_locations.location_ID IN (1, 2, 3, 5, 7, 12, 13, 26, 27, 28, 29, 30, 31, 34, 35, 36, 38, 39, 40, 41, 42, 43, 44, 46, 49, 52, 53, 54, 55, 56, 60, 62, 64, 65, 66, 67, 68, 69, 70, 72, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 89, 90, 97, 107, 10, 21, 32, 33, 37, 51, 4, 6, 8, 9, 11, 14, 15, 16, 17, 18, 19, 20, 22, 23, 24, 25, 45, 47, 48, 50, 57, 58, 59, 61, 63, 71, 73, 84, 85, 86, 87, 88, 91, 92, 93, 94, 95, 96, 98, 99, 100, 101, 102, 103, 104, 105, 106, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160)
GROUP BY deals.deal_ID;
但仍然顯示超過5個記錄同一地點。
編輯2:我試過UNION ALL
的方法,似乎是工作。現在我得到了30行的總結果,但我關心查詢的大小。
這裏是我的查詢看起來像現在:http://pastebin.com/r6vyG594
的explain
是巨大的,所以我不能發佈到網上。我應該怎麼做才能使查詢效率更高,規模更小?
執行大約需要0.2158秒。
請勿在您的帖子中包含簽名:http://stackoverflow.com/faq#signatures – Tchoupi
http://stackoverflow.com可能存在重複/ questions/2129693/mysql-using-limit-group-by-to-get-n-results-per-group – gtgaxiola
來自其他查詢的'$ location_IDs'? – sebastian