你的位置:首页 > 软件开发 > 数据库 > [django/mysql] 使用distinct在mysql中查询多条不重复记录值的解决办法

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

发布时间:2016-01-15 16:00:03
前言:不废话.,直接进入正文正文:如何使用distinct在mysql中查询多条不重复记录值?首先,我们必须知道在django中模型执行查询有两种方法:第一种,使用django给出的api,例如filter value distinct order_by等模型查询api;代码:L ...

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

正文:

如何使用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'


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

关键词:MYSQL

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。