Mysql从连接中检索特定的分组行数

时间:2017-08-09 14:33:20

标签: php mysql

所以我创建了这个查询

SELECT a.email
     , a.password
     , a.server
     , a.status
     , a.step
     , b.*
  FROM mail a 
  JOIN automation_logs b 
    ON b.accountid = a.accountid 
 WHERE a.status <0 
 ORDER 
    BY b.created DESC;

它的用途实际上是我试图从我们的日志表中获取在我们的api上出错的电子邮件帐户的调试信息。 automation_logs表本质上是由我们的API生成的错误消息的文本转储。

这个查询给了我想要的东西,但给了我太多。我只希望最近的五个(读取:创建的字段是时间戳)任何帐户的错误消息,因为其中一些帐户已存在多年,旧的错误已得到修复,并且不需要知道&# 39; s破碎,只是填补结果。

单个查询是否可以实现这一目标?

1 个答案:

答案 0 :(得分:0)

遵循此处列出的建议:Thank you Marshal Tigerus

我能够使用以下sql:

SET @currcount = NULL, @currvalue = NULL;

SELECT a.email,a.password,a.serverid,a.status,a.step,b.message,b.created FROM mail as a JOIN (
    SELECT * FROM (
        SELECT
            *,
            @currcount := IF(@currvalue = accountid, @currcount + 1, 1) AS num,
            @currvalue := accountid AS cur_id
        FROM automation_logs
        WHERE message NOT LIKE ""
        ORDER BY accountid, created DESC
    ) as limitedresults WHERE num <= 5
) as b ON a.accountid = b.accountid WHERE a.status < 0 ORDER BY b.created DESC