doukui4836 2009-05-27 06:06
浏览 19
已采纳

通讯队列的复杂MySQL查询

Hey everyone, I'm back and looking forward to more of your brilliance. I have two tables:

  1. newsletters — each row contains a 'id', 'subject', 'body' & 'from' headers for an email
  2. newsletter_queue — each row contains an 'id', 'email' address, 'date' added to queue and the 'newsletterid'

My goal is to develop a MySQL query that can pull x amount of rows from 'newsletter_queue', then group them by their 'newsletterid' while using GROUP_CONCAT (or whatever works) to put all the emails into a character separated string which I will parse with PHP. The reason I'd like to have them together is because the mailer library I am using (swiftmailer) accepts an array with emails for batch emails. Also, if possible, it would be very neat to join the two tables together, thereby avoiding a second query.

Here's what I have so far:

SELECT GROUP_CONCAT(email ORDER BY date ASC SEPARATOR '|'), newsletterid, date
FROM newsletter_queue
WHERE status='0'
GROUP BY newsletterid
LIMIT 125

My problem is that the LIMIT 125 is being applied to the already concatenated rows, rendering it useless due to the fact that I'm trying to limit the amount of total emails being sent at a time, not unique newsletters. If anyone could guide me in the right direction, I would be very appreciative. If you wind up writing the example, that's great too.

  • 写回答

3条回答 默认 最新

  • dounue1965 2009-05-27 06:20
    关注
    SELECT GROUP_CONCAT(email ORDER BY date ASC SEPARATOR '|'), newsletterid, date
    FROM 
       (SELECT email, newsletterid, date 
        FROM newsletter_queue
        WHERE status="0"
        ORDER BY date ASC
        LIMIT 125) as Unsent
    GROUP BY newsletterid
    

    This applies the limit to the inner query, before the group by statement is executed. It doesn't matter that the group by statement is in the outer query since a group by will need a temporary table and sort anyway. If you need some kind of ordering of the concatenated result, you can just apply it to the outer query, for instance by applying max or min to date and order by it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥50 用AT89C52单片机设计一个温度测量与控制电路
  • ¥15 无法import pycausal
  • ¥15 VS2022创建MVC framework提示:预安装的程序包具有对缺少的注册表值的引用
  • ¥15 weditor无法连接模拟器Local server not started, start with?
  • ¥20 6-3 String类定义
  • ¥15 嵌入式--定时器使用
  • ¥20 51单片机学习中的问题
  • ¥30 Windows Server 2016利用兩張網卡處理兩個不同網絡
  • ¥15 Python中knn问题
  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库