当前位置:Gxlcms > 数据库问题 > [django/mysql] 使用distinct在mysql中查询多条不重复记录值的解决办法

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

时间:2021-07-01 10:21:17 帮助过:5人阅读

>>> 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中查询多条不重复记录值的解决办法

标签:

人气教程排行