2015-10-26 53 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

请再次看到问题,我已编辑它。 –