4

PostgreSQL 쿼리의 결과를 참/거짓 수만큼 순서 지정해야합니다. 예를 들어Postgresql : 참 OR 절의 수로 랭크를 계산하십시오.

SELECT * FROM mytable WHERE cond1 OR cond2 OR cond3 ORDER BY rank DESC 

과 같은 검색어는 조건 수에 따라 결과를 평가해야합니다. 또한보기/저장 프로 시저로이 문제를 해결하는 접근법도 매우 환영합니다!

답변

5

반복 조건 및 추가 :

SELECT * FROM mytable 
WHERE fld = 'A' OR fldB = CURRENT_DATE OR fldC = 7 
ORDER BY 
    (fld = 'A')::int + (fldB = CURRENT_DATE)::int + (fldC = 7)::int 
DESC 
-2
The above query will check those conditions from the left side one by one i.e 

if the cond1 is true then 
     return the results order by rank. 
if cond1 is false and cond2 is true then 
     return the results order by rank. 
if cond1 and cond2 both are false but cond3 is true 
     returns the results order by rank. 
if all conditions are false then no result is returned.  

So in brief it doesn't check all the conditions simultaneously for OR conditions. 


Thanks. 
+0

예상되는 쿼리 동작의 요약입니다. 예 : –

2

뭔가이 아마 같은 :

select * 
from (
    SELECT * , case when cond1 then 1 else 0 end 
      + case when cond2 then 1 else 0 end 
      + case when cond3 then 1 else 0 end as cond_count 
    FROM mytable 
    WHERE cond1 
     OR cond2 
     OR cond3 
) t 
order by cond_count desc 

이 솔루션에 대한 추한 것은 당신이 문에 두 번 모든 조건을 가지고있다, 그러나 나는 지금 다른 해결책을 생각할 수 없다.

+0

'CASE' 키워드를 생략 할 수 있습니까? – vyegorov

+0

@vyegorov : 물론 아닙니다. 그 점을 지적 해 주셔서 감사합니다. –

+0

@a_horse_with_no_name : 사용자가 집계하고 싶다고 생각하지 않습니다. CASE 문을 추가하십시오. 또한 subselect를 제거하고 표현식을'ORDER BY' 절에 넣을 수 있습니다. –