如何查找ID的最后记录和按时间检查?

时间:2016-03-01 06:57:51

标签: mysql

这是我的主表,其中包含此类记录

id  | a_id | datetime
------------------------
1   |   1  | 2016-01-07 15:42:14
2   |   1  | 2016-01-08 16:42:14
3   |   1  | 2016-01-09 17:42:14
4   |   2  | 2016-01-07 15:42:14
5   |   2  | 2016-01-08 16:42:14
6   |   2  | 2016-01-09 17:42:14
7   |   2  | 2016-01-10 18:42:14
8   |   2  | 2016-01-11 19:42:14

我希望输出如下:

假设我当前的时间是17:50:00,所以我的下面的结果在我当前时间的半小时之前插入。

id  | a_id | amount
------------------------
3   |   1  | 2016-01-09 17:42:14

我怎样才能获得这种输出?

4 个答案:

答案 0 :(得分:1)

试试这个

from io import BytesIO    

from flask import Flask, send_file


app = Flask(__name__)


@app.route('/test_download', methods=['POST'])
def test_download():
    # Use BytesIO instead of StringIO here.
    buffer = BytesIO()
    buffer.write(b'jJust some letters.')
    # Or you can encode it to bytes.
    # buffer.write('Just some letters.'.encode('utf-8'))
    buffer.seek(0)
    return send_file(buffer, as_attachment=True,
                     attachment_filename='a_file.txt',
                     mimetype='text/csv')


if __name__ == '__main__':
    app.run(debug=True)

答案 1 :(得分:1)

类似应该工作的东西 如果max(a_id)dosent工作,那么你也应该把datetime字段名称,但首先使用sql转换为字符串

sudo pip install --upgrade https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.7.1-cp27-none-linux_x86_64.whl

答案 2 :(得分:0)

这样的事情应该有效:

SELECT *
FROM mytable
WHERE `datetime` BETWEEN DATE_ADD(NOW(), INTERVAL -30 MINUTE) AND NOW()

Demo here

修改

要获取最新的每组记录,然后查找这些记录是否在指定的时间间隔内,您可以使用以下查询:

SELECT id, a_id, `datetime`
FROM (
  SELECT id, a_id, `datetime`,
         @rn := IF(@aid = a_id, @rn + 1,
                   IF(@aid := a_id, 1, 1)) AS rn
  FROM mytable
  CROSS JOIN (SELECT @rn := 0, @aid := 0) AS vars
  ORDER BY a_id, `datetime` DESC) AS t
WHERE t.rn = 1 AND 
      `datetime` BETWEEN DATE_ADD(NOW(), INTERVAL -30 MINUTE) AND NOW()

Demo here

答案 3 :(得分:0)

如果有人过度思考这个......

SELECT *
  FROM main 
 WHERE datetime < NOW() - INTERVAL 30 MINUTE 
 ORDER
   BY datetime DESC 
  LIMIT 1;