How should I declare a query to only use DISTINCT on not null values for certain column but still keep the records for which the column value is null, I'm trying to modify the following query:
我如何声明一个查询只对某列的非空值使用不同的值,但仍然保留列值为空的记录,我正在修改以下查询:
I'm trying to modify the following query,
我正在修改下面的查询,
So, basically I want the second query to return all the messages grouped by parent_id
when the parent_id
column IS NOT NULL and return ALL the records when parent_id
IS NULL.
因此,基本上,我希望第二个查询在parent_id列不为NULL时返回根据parent_id分组的所有消息,并在parent_id为NULL时返回所有记录。
I'm using PG 9.0.4 and Rails 3.1 - any help would be appreciated, thanks!
我正在使用PG 9.0.4和Rails 3.1 -任何帮助都将是感激的,谢谢!
1 个解决方案
#1
5
Select Distinct ON (parent_id) *
from messages
WHERE parent_id IS NOT NULL
UNION
Select * from messages where parent_id IS NULL
#1
5
Select Distinct ON (parent_id) *
from messages
WHERE parent_id IS NOT NULL
UNION
Select * from messages where parent_id IS NULL