2017-10-07 58 views
0

我有contacts具有id | city_id | category_id |電子郵件字段的表。
基本的查詢是mysqli:爲IN ID中的每一個選擇查詢和限制

" 
SELECT id 
    , email 
    FROM contacts 
WHERE city_id IN (".implode(',', $arrCity).") 
    AND category_id IN (".implode(',', $arrCategory).") 
" 

但我需要設置一個限制:10排在城市的各個類別。可能嗎?

+0

請參閱https://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-to-be-a-very-simple- sql-query – Strawberry

回答

0

這很棘手。在MySQL中,最簡單的方法是使用變量:

SELECT id, email 
FROM (SELECT c.*, 
      (@rn := IF(@cc = CONCAT_WS(':', city_id, category_id), @rn + 1, 
         IF(@cc := CONCAT_WS(':', city_id, category_id), 1, 1) 
         ) 
      ) as rn 
     FROM (SELECT c.* 
      FROM contacts c 
      WHERE city_id IN (".implode(',', $arrCity).") AND 
        category_id IN (".implode(',', $arrCategory).") 
      ORDER BY city_id, category_id 
      ) c CROSS JOIN 
      (SELECT @cc := '', @rn := 0) params 
    ) c 
WHERE rn <= 10; 

這枚舉了每個城市/類別組合中的行。外WHERE限制在每個組合10。

+0

現在我在'(@rn = IF(@cc = CONCAT_WS(':',city_id,category_id),@rn + 1''字段列表'中有'未知列'city_id'這是奇怪的 – fiter

+0

@Fiter。。。'city_id'在你原來的查詢中。 –

+0

爲什麼會這樣downvoted? –