简体   繁体   English

PostgreSQL:你如何 SELECT DISTINCT 关系和不同字段的顺序取决于 WHERE 子句?

[英]PostgreSQL: how do you SELECT DISTINCT relations and order by different fields depending on WHERE clause?

Each account is associated with one person and one type of account.每个帐户都与一个人和一种帐户相关联。 I want to SELECT a distinct subset of accounts.我想 SELECT 一个不同的帐户子集。 In order to be selected the accounts have meet at least one of two criteria.为了被选中,帐户至少满足两个标准之一。 If an account occurs twice如果一个帐户出现两次

I want to order this result set based on two different fields.我想根据两个不同的字段订购这个结果集。 This was my attempt:这是我的尝试:

Select DISTINCT a.*
FROM people AS p
JOIN accounts AS a
ON a.people_id = p.id
JOIN type_account AS t
ON t.type_id = a.id
WHERE t.id IN(1,3,5)
OR p.id IN(2,4,6)
ORDER BY(CASE
         WHEN p.id IN(2,4,6) THEN p.updated_at
         WHEN t.id IN(1,3,5) THEN p.created_at) AS position

And I got this error: SELECT DISTINCT, ORDER BY expressions must appear in select list我得到了这个错误: SELECT DISTINCT, ORDER BY expressions must appear in select list

If I move the case statement to the select it possible for one account (associated with different people) to appear in the results twice, ie once when the first where clause is met and twice when the second where clause is met.如果我将 case 语句移至 select,则一个帐户(与不同的人相关联)可能会出现在结果中两次,即在满足第一个 where 子句时出现一次,在满足第二个 where 子句时出现两次。 In this case the accounts will be appearing twice in the result set.在这种情况下,帐户将在结果集中出现两次。

I am having trouble wrapping my head around this one.我很难理解这个问题。 Any help would be appreciated:)任何帮助,将不胜感激:)

Move your CASE statement(s) into the SELECT clause, then order on their position:将您的 CASE 语句移动到 SELECT 子句中,然后在其 position 上订购:

SELECT
    CASE
        WHEN p.id IN(2,4,6) THEN p.updated_at
        WHEN t.id IN(1,3,5) THEN p.created_at
    END AS position,
    DISTINCT a.*
FROM people AS p
JOIN accounts AS a
ON a.people_id = p.id
JOIN type_account AS t
ON t.type_id = a.id
WHERE t.id IN(1,3,5)
OR p.id IN(2,4,6)
ORDER BY 1 DESC
LIMIT 1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM