【问题标题】:Postgres: Could not choose a best candidate functionPostgres:无法选择最佳候选函数
【发布时间】:2017-04-25 09:16:04
【问题描述】:

有人能解释一下如何解决这个查询吗?

SELECT date_part('month', scheduler_scheduleevents.date), sum(price)
    FROM user_settings_userservices
    JOIN scheduler_scheduleevents
    ON scheduler_scheduleevents.service_type_id = user_settings_userservices.id
    WHERE user_settings_userservices.salonid_id = %s
    AND is_start_time = True and is_active = False
    AND ( date < %s or ( date = %s and time < %s ) )
    AND date_part('year', scheduler_scheduleevents.date) = date_part('year', %s)
    GROUP BY date_part('month', scheduler_scheduleevents.date),
    (request.user.id, now_date, now_date, now_time, now_date, )
    )

当我尝试在 django 应用程序中执行此查询时,我收到此警告:

function date_part(unknown, unknown) is not unique

LINE 9: ...ate_part('year', scheduler_scheduleevents.date) = date_part(...
                                                         ^

HINT:  Could not choose a best candidate function. You might need to add explicit type casts.

【问题讨论】:

  • 发布select version()和psql的\d scheduler_scheduleevents的输出

标签: python sql django postgresql


【解决方案1】:

你应该添加一个显式转换:

AND date_part('year', scheduler_scheduleevents.date::date) = date_part('year', %s::date)

当 postgres 无法确定执行哪个实际函数时,您会收到此错误。

Postgres 重载了 date_part 函数,它有一个版本用于 timestamp 作为第二个参数,另一个版本用于 interval 第二个参数:date_part(text, timestamp) 和 @ 987654324@.

当您说date_part('year', %s) 时,postgres 不知道它是否应该将您的%s 参数解释为时间戳间隔。因此,它需要您将 %s 参数转换为仅与 date_part 函数的这两个版本之一匹配的类型。当您将 %s 转换为 date 时(即当您编写 %s::date 时)postgres 只能使用函数的第一个重载,因为 date 可以自动转换为 timestamp 但不能自动转换为 interval

【讨论】:

    猜你喜欢
    • 2013-03-20
    • 1970-01-01
    • 2017-08-31
    • 1970-01-01
    • 1970-01-01
    • 2015-09-16
    • 1970-01-01
    • 1970-01-01
    • 2015-06-27
    相关资源
    最近更新 更多