【问题标题】:How can I sort a database by date?如何按日期对数据库进行排序?
【发布时间】:2019-01-17 20:37:12
【问题描述】:

我正在创建一个 Python 应用程序,它将我的作业存储在数据库中(使用 PhpMyAdmin)。我的问题来了:

此时,我正在使用 ID(1、2、3、4...)、日期(23/06/2018...)和任务(阅读 a 的一章)对每个输入进行排序书)。现在我想按日期对它们进行排序,因为当我想阅读我必须做的事情时。我更愿意先看看我应该做什么,这取决于我应该什么时候完成。例如:

如果我有两个任务:一个 25/07/2018 和另一个 11/07/2018,我想先显示 11/07/2018,不管它是否晚于 25/07/ 2018 年。我正在使用 Python (3.6)、pymysql 和 PhpMyAdmin 来管理数据库。

我有个想法让这个工作,也许我可以每 2 小时运行一次 Python 脚本,对数据库中的所有元素进行排序,但我不知道该怎么做。

现在,我将向您展示将值输入数据库的代码,然后将它们全部显示出来。

def dba():
  connection = pymysql.connect(host='localhost',
                             user='root',
                             password='Adminhost123..',
                             db='deuresc',
                             charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor)

  try:
    with connection.cursor() as cursor:
        # Create a new record
        sql = "INSERT INTO `deures` (`data`, `tasca`) VALUES (%s, %s)"
        cursor.execute(sql, (data, tasca))

    # connection is not autocommit by default. So you must commit to save
    # your changes.
    connection.commit()
    with connection.cursor() as cursor:
        # Read a single record
        sql = "SELECT * FROM `deures` WHERE `data`=%s"
        cursor.execute(sql, (data,))
        resultat = cursor.fetchone()
        print('Has introduït: ' + str(resultat))
  finally:
    connection.close()

def dbb():
  connection = pymysql.connect(host='localhost',
                             user='root',
                             password='Adminhost123..',
                             db='deuresc',
                             charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor)
  try:
    with connection.cursor() as cursor:
        # Read a single record
        sql = "SELECT * FROM `deures`"
        cursor.execute(sql)
        resultat = cursor.fetchall()
        for i in resultat:
            print(i)        
  finally:
    connection.close()

有人可以帮忙吗?

【问题讨论】:

  • SELECT * FROM table ORDER BY date

标签: python sql python-3.x phpmyadmin pymysql


【解决方案1】:

您不对数据库进行排序。当您请求数据时,您对查询的结果进行排序。所以在你的dbb 函数中你应该这样做:

SELECT * FROM `deures` ORDER BY `data`

假设data 是带有日期的字段。

【讨论】:

  • 同月有效。例如:2018 年 6 月 23 日、2018 年 6 月 28 日、2018 年 6 月 30 日,但如果不是同一个月,则停止工作。我的意思是它只考虑一天,所以如果还有一个月,它会打印:23/06/2018、28/06/2018、29/10/2018、30/06/2018。有没有办法解决这个问题?
  • 您的列是什么类型的?您应该使用 DATE 类型。
猜你喜欢
  • 2016-03-25
  • 2011-09-08
  • 2020-06-04
  • 2016-10-15
  • 1970-01-01
  • 1970-01-01
  • 2016-11-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多