【问题标题】:select all columns from a table where the combination of 3 fields is unique从表中选择所有列,其中 3 个字段的组合是唯一的
【发布时间】:2022-01-05 20:36:43
【问题描述】:

我正在尝试使用带有 MySql 后端的 django ORM 选择具有多个列的表中的所有条目,其中 3 个特定列的组合是不同的。

id first_name last_name n_children some_stuff other_stuff date
1 john silver 2 any any 2021-01-01
2 john silver 3 any any 2021-01-01
3 john white 2 some some 2021-01-01
4 john silver 2 some some 2021-01-02

我需要选择“first_name”、“last_name”和“n_children”的组合唯一的所有行,优先考虑最近的条目。在本例中,结果应该是 id 为 [2,3,4] 的行。

我的尝试

qs = Table.objects.all().order_by('-date').annotate(
    unique_value=Concat('first_name','last_name','n_children', output_field=TextField())
).distinct('unique_value')

但这不起作用,因为我使用的是 mysql,我得到了这个错误

django.db.utils.NotSupportedError: DISTINCT ON fields is not supported by this database backend

【问题讨论】:

  • 我改用 postgresql 的原因之一。这并不容易,但现在我认为这是一个不错的选择。 Postgres 与 django 的集成度最好。

标签: mysql python-3.x django


【解决方案1】:

这实际上无法用distinct() 完成。它可能无法用 Django ORM 完成。用原始 SQL 试试:

Table.objects.raw("""
    SELECT * FROM table GROUP BY first_name, last_name, n_children ORDER BY date DESC
""")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-08
    • 1970-01-01
    • 2021-03-14
    • 2011-03-29
    相关资源
    最近更新 更多