每个连接列获得有限的行数

时间:2016-03-17 14:15:51

标签: mysql

我现在有以下SQL语句:

SELECT m . *
FROM newsletter_mail_list m
INNER JOIN (
    SELECT n.id
    FROM newsletter n
    GROUP BY n.customer_id
    ORDER BY n.id ASC
) b ON m.newsletter_id = b.id
WHERE m.sent_date IS NULL 

邮件列表表

+--------+-------+--------+--------+-----+
| id | newsletter_id | email | sent_date |
+--------+-------+--------+--------+-----+
| 1  | 8             | abcd  | today     |
| 2  | 8             | cfdf  | NULL      |
| 3  | 8             | afdg  | NULL      |
| 4  | 9             | zfbh  | NULL      |
| 5  | 9             | eerg  | NULL      |
| 6  | 9             | ertg  | NULL      |
| 7  | 9             | zfbh  | NULL      |
| 8  | 9             | eerg  | NULL      |
| 9  | 9             | ertg  | NULL      |
| 10 | 9             | zfbh  | NULL      |
| 11 | 9             | eerg  | NULL      |
| 12 | 9             | ertg  | NULL      |
| 13 | 9             | zfbh  | NULL      |
| 14 | 9             | eerg  | NULL      |
| 15 | 9             | ertg  | NULL      |
| 16 | 9             | zfbh  | NULL      |
| 17 | 9             | eerg  | NULL      |
| 18 | 9             | ertg  | NULL      |
+--------+-------+--------+--------+-----+

期望的结果

+--------+-------+--------+--------+-----+
| id | newsletter_id | email | sent_date |
+--------+-------+--------+--------+-----+
| 2  | 8             | cfdf  | NULL      |
| 3  | 8             | afdg  | NULL      |
| 4  | 9             | zfbh  | NULL      |
| 5  | 9             | eerg  | NULL      |
| 6  | 9             | ertg  | NULL      |
| 7  | 9             | zfbh  | NULL      |
| 8  | 9             | eerg  | NULL      |
| 9  | 9             | ertg  | NULL      |
| 10 | 9             | zfbh  | NULL      |
| 11 | 9             | eerg  | NULL      |
| 12 | 9             | ertg  | NULL      |
| 13 | 9             | zfbh  | NULL      |
+--------+-------+--------+--------+-----+

这个给了我所有mail_list行,其中sent_date为NULL,外国时事通讯是客户中最早的。

现在我只想要为子选择返回的每个时事通讯返回最多10个mail_list行。

示例:

到目前为止,我通过这个SQL获得了21个结果,3个mail_lists属于时事通讯8和18个结果的时事通讯9。 但是时事通讯9的结果数量应该只有10个。

我怎么能用SQL做到这一点?这甚至可能吗?

1 个答案:

答案 0 :(得分:1)

例如:

SELECT x.*
  FROM mail_list x 
  JOIN mail_list y 
    ON y.newsletter_id = x.newsletter_id 
   AND y.id <= x.id 
 WHERE x.sent_date IS NULL 
 GROUP 
    BY newsletter_id
     , id 
HAVING COUNT(*) <= 10;

如果性能问题,那么带变量的解决方案会更快......

E.g:

SELECT id
     , newsletter_id
     , email
  FROM 
     ( SELECT x.*
            , CASE WHEN @prev=newsletter_id 
                   THEN @i:=@i+1 
                   ELSE @i:=1 END i
            , @prev:=newsletter_id prev 
         FROM mail_list x
            , (SELECT @prev:='',@i:=0) vars 
        WHERE sent_date IS NULL
        ORDER 
           BY newsletter_id, id
     ) a
 WHERE i <= 10;