2015-10-26 52 views
-1

我在sql中寫了一個查詢,其中包含group by子句。使用group by子句時,sql查詢不起作用

group by子句是在既不是主鍵或唯一鍵的屬性時,我在不同的地方都讀到,當我們使用MySQL的一般需任意行,但在PostgreSQL的,它不以相同的方式表現。 所以我在編寫查詢時使用了聚合函數。

我寫的查詢是:

select user_id, min(priority) from table where is_active = 'false' group by user_id; 

此查詢工作正常,但是當我試圖讓其他任何屬性信息,我得到一個錯誤。

新查詢:

select id,user_id, min(priority) from table where is_processed='false' group by user_id; 

和錯誤是:

column "table.id" must appear in the GROUP BY clause or be used in an aggregate function. 

我失去的東西?

說明:

按答案表明,我應該使用ID或其他任何東西,我需要group by子句後進行選擇。 但它會改變這個概念。 假設我有一個表「Pending_Entries」。它包含一些屬性,如id,userd_id,is_active和priority。 現在我需要找到對應於user_iduser_id and the minimum priority。爲此,我使用了最初的查詢,它工作得很好。現在假設我也需要id

我該怎麼辦?

+0

隨着錯誤消息意味着,任何列,它是不是聚合函數必須出現在「GROUP BY」子句中。如果你想要列'id'和'user_id',你必須在'GROUP BY'子句中重複它們。 –

+0

用'group by user_id'表示您希望每個'user_id'有一個結果行。那麼,如果表中的一個'user_id'有不同的ID,你想顯示什麼'id'?對於'priority',你決定顯示每個'user_id'的最小優先級。你對'id'的決定是什麼? –

+0

@ThorstenKettner:Id在這種情況下是唯一的 –

回答

1

列的誤差是正常的; MySQL不正確。在Postgres裏,你可以使用distinct on

select distinct on (user_id) t.* 
from table t 
where is_processed = 'false' 
order by user_id, prioirty asc; 

在MySQL中,您查詢的工作語法,但它不是做你想要什麼。它爲不在group by而不在聚合函數中的列返回任意值。

有很多種方法,可以讓兩個系統查詢工作:

select t.* 
from table t 
where t.is_processed = 'false' and 
     t.priority = (select min(t2.priority) 
        form table t2 
        where t2.user_id = t.user_id and t2.is_processed = 'false' 
        ); 
+0

這工作正常,但我不想使用嵌套查詢 –

0

試試這個:

select id,user_id, min(priority) from table where is_processed='false' group by user_id, id, priority; 

希望這有助於。

+0

請再次看到問題,我已編輯它。 –

0

從您的錯誤消息中可以明顯地看出問題,不是嗎?

包括在你的GROUP BY

select id,user_id, min(priority) from table where is_processed='false' group by id,user_id,priority; 
0

後添加列'ID「組由」

select id,user_id, min(priority) from table where is_processed='false' group by user_id, id; 
+0

請再次看到問題,我已編輯它。 –