我使用以下代码从数据库中获取值:
但是当我编写这段代码(测试以查看问题出在哪里......)时,我注意到查询没有从数据库中取出不同的值:
这是查询
select distinct(ca.id)as id, acc.name as accName,pIsu.name as pareentIsu, sIsu.name as subIsu ,
dv.domain_value as contractType,acc.id as accId,dvct.domain_value as contractstatus
from contracts_account ca left join business_unit pIsu on ca.parent_isu_fk = pIsu.id
left join business_unit sIsu on ca.sub_isu_fk = sIsu.id
left join business_unit acc on ca.account_fk = acc.id
left join contracts con on con.contracts_account_fk = ca.id
left join domain_values dv on dv.id = con.contract_type_fk
left join domain_values dvct on dvct.id = con.contract_status_fk
where ca.id is not null and con.contract_type_fk in ( 4466079 ) order by ca.id
此查询根本不会返回'Distinct Id ' 我究竟做错了什么? 我正在使用postgres 8.2
答案 0 :(得分:7)
您的查询被解释为:
select distinct (ca.id) as id, acc.name as accName, . . .
这是一个标准的distinct
声明。如果您希望每ca.id
行只有一行包含第一行的值(基于order by
),请使用distinct on
:
select distinct on (ca.id) ca.id, acc.name as accName, . . .
答案 1 :(得分:1)
您是否尝试使用PostgreSQL的DISTINCT ON语法?
http://www.postgresql.org/docs/current/static/sql-select.html#SQL-DISTINCT
即。错过了ON?