Postgres:无法选择最佳候选功能

时间:2016-12-09 20:11:17

标签: python sql django postgresql

有人可以解释如何修复此查询吗?

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 app中执行此查询时,我收到此警告:

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.

1 个答案:

答案 0 :(得分:1)

您应该添加一个显式的强制转换:

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

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

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

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