sql根据其他表选择时间戳之前的最新10个条目

时间:2017-09-02 19:46:20

标签: mysql sql

我想按用户为每个错误选择10个以前的日志条目:

table errors
    user, timestamp, status_code
    1, 2017-01-01 20:00, 404
    2, 2017-01-01 18:00, 404
    1, 2017-01-01 15:00, 401

table log
    user, timestamp
    1, 2017-01-01 19:55
    2, 2017-01-01 19:55
    4, 2017-01-01 19:55
    1, 2017-01-01 19:54
    1, 2017-01-01 19:52
    ...

E.g。用户1在20:00发生错误。因此,我想在20:00之前为用户1选择最新的10个日志条目:

SELECT * FROM log WHERE user = 1 AND timestamp <= 20:00 ORDER BY timestamp DESC LIMIT 10

但是,我希望使用status_code 404

对错误表中的所有条目执行此操作

2 个答案:

答案 0 :(得分:0)

使用左连接您可以根据另一个表获取值。 例如:

  

从first_table_name中选择a。,b。作为左连接second_table_name As b on a.id = b.user_id其中b.timestamp&lt; =&#39; value&#39;

这将解决您的难题。

答案 1 :(得分:0)

您可以在ROW_NUMBER()列中使用user分区,但由于MySQL不支持,您需要使用变量进行模拟:

SELECT user, timestamp, row_number FROM (
  SELECT @row_number:=CASE WHEN @user=user THEN @row_number+1 ELSE 1 END AS row_number,
    @user:=user AS user, timestamp
  FROM (SELECT log.*, errors.timestamp as error_timestamp
    FROM log
    JOIN errors on errors.user=log.user
    WHERE status_code=404) AS log_404,
    (SELECT @row_number:=0,@user:='') AS variables
  WHERE timestamp<=error_timestamp
  ORDER BY user, timestamp DESC
) AS ranked_log
where row_number<=10;

这些博客条目解释了MySQL中用于模拟ROW_NUMBER()的技巧:

MySQL – Generating Row Number for Each Row Using Variable

MySQL – Reset Row Number for Each Group – Partition By Row Number