爲什麼這個查詢:爲什麼Postgres允許我的列不在組中?
SELECT inv.batch_number_id AS batch_number_id,
inv.expiry_date AS expiry_date,
inv.facility_id AS facility_id,
inv.id AS id,
fac.code AS facility_code,
inv_st.description AS status,
bn.batch_nbr AS batch_number,
bn.expiry_date AS batch_expiry_date,
sum(CASE WHEN al.status_id < 90 THEN al.alloc_qty ELSE 0 END) AS alloc_qty
FROM inventory inv
INNER JOIN facility fac ON inv.facility_id = fac.id
INNER JOIN inventory_status inv_st ON inv.status_id = inv_st.id
LEFT OUTER JOIN batch_number bn ON inv.batch_number_id = bn.id
LEFT OUTER JOIN allocation al ON al.from_inventory_id = inv.id
GROUP BY inv.id,
facility_code,
status,
batch_number,
batch_expiry_date
在Postgres的9.1.6工作?
來自文檔:「當存在GROUP BY時,除了集合函數內,SELECT列表表達式無法引用未分組的列,因爲對於未分組的列將有多個可能的值返回。 「
如果我將fac.id
添加到select表達式中,我得到預期的「ERROR:column」fac.id「必須出現在GROUP BY子句中或用於聚合函數中」。爲什麼postgres抱怨這個專欄但忽略了facility_id? (這裏是一大堆在原來的查詢也違揹我以同樣的方式期望其他列的例子是縮短了清晰度。)
顯示錶結構'\ d inventory'' \ d facility'''d inventory_status'。這裏的關鍵術語是'函數依賴關係' –
從手冊:「*當存在GROUP BY時,SELECT列表表達式無法引用除聚合函數**之外的未分組列,或者未分組列在功能上依賴在分組列上** [...]如果分組列(或其子集)是包含未分組列的表的主鍵,則存在函數依賴項。*「 –