mysqli:为每个IN id选择查询和限制

时间:2017-10-07 18:58:29

标签: mysql mysqli

我有contacts表,其中包含id | city_id | category_id |电子邮件字段 基本查询是

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

但是我需要设置一个限制:城市中每个类别有10行。有可能吗?

1 个答案:

答案 0 :(得分: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。