• [django/mysql] 使用distinct在mysql中查询多条不重复记录值的解决办法


    前言:不废话.,直接进入正文

    正文:

    如何使用distinct在mysql中查询多条不重复记录值?

    首先,我们必须知道在django中模型执行查询有两种方法:

    第一种,使用django给出的api,例如filter value distinct order_by等模型查询api;

    代码:LOrder.objects.values('finish_time').distinct()

    这里应注意,原官方文档中写到:

    示例(第一个之后的示例都只能在PostgreSQL 上工作):

    >>> Author.objects.distinct()
    [...]
    
    >>> Entry.objects.order_by('pub_date').distinct('pub_date')
    [...]
    
    >>> Entry.objects.order_by('blog').distinct('blog')
    [...]
    
    >>> Entry.objects.order_by('author', 'pub_date').distinct('author', 'pub_date')
    [...]
    
    >>> Entry.objects.order_by('blog__name', 'mod_date').distinct('blog__name', 'mod_date')
    [...]
    
    >>> Entry.objects.order_by('author', 'pub_date').distinct('author')
    

    因为我使用的mysql数据库,所以在distinct只能是第一中用法,或者可以这样用

    LOrder.objects.values('finish_time').distinct().order_by('finish_time')

    第二种,使用原始SQL查询

    LOrder.objects.raw('SELECT DISTINCT id,finish_time FROM keywork_lorder group by finish_time')

    上面直接使用mysql语句进行剔重,这里需要特别注意的是:

    一是原始SQL查询只有一种字段不可以被丢掉,官方文档中这样说道:

    只有一种字段不可以被省略——就是主键。 Django 使用主键来识别模型的实例,所以它在每次原始查询中都必须包含。 如果你忘记包含主键的话,会抛出一个InvalidQuery异常。

    意思是,如果你的sql语句是这样的'SELECT DISTINCT finish_time FROM keywork_lorder ',那么将会报错Raw query must include the primary key,就是id字段不能被丢掉!

    二是,这里是原始mysql查询语句,mysql去掉重复项要这样写:'SELECT DISTINCT id,finish_time FROM keywork_lorder group by finish_time'

  • 相关阅读:
    python的性能了解
    工作记录01/17/11
    继承或者重写django的user model?
    dunder=double underscore
    ipython应该是个好的命令行式的python ide,不过现在没时间折腾。
    django的settings如何在不同环境下进行切换
    pythonic实践
    关于递归函数的简单认识
    数据结构(C语言版)链表相关操作算法的代码实现
    数据结构(C语言版)顺序栈相关算法的代码实现
  • 原文地址:https://www.cnblogs.com/CQ-LQJ/p/5133390.html
Copyright © 2020-2023  润新知