SQL在每个列上都不同但只有一个(id)

时间:2014-04-29 06:02:21

标签: sql postgresql

是否可以进行此类操作?我有结构表:

id(unique, serial), parameter(text), description(text), severity(text), topic_id(int, foreign key)

允许用户添加相同的行(具有相同的parameterdescriptiontopic_idseverity但具有不同的id

执行查询时:

SELECT DISTINCT PARAMETER,
                description,
                severity
FROM task
WHERE topic_id=851;

导致

  parameter     | description     | severity | 
----------------+-----------------+----------+
do when possible| ask bob         | 0        |      
      time diff | check time serv | 2        |      
         urgent | fix it asap     | 3        |      
         test   | no details aval | 3        |      
         test2  | no details aval | 2        |      
         test3  | no details aval | 2        |      

我得到6 rows包含我想要的信息的结果。但是,我需要此查询为每行返回id(因此我可以在服务器端正确处理它)

当我将查询更改为:

SELECT DISTINCT id,
                PARAMETER,
                description,
                severity
FROM task
WHERE topic_id=851;

 id   |  parameter      | description     | severity | 
------+-----------------+-----------------+----------+
 30045| do when possible| ask bob         | 0        |      
 30046| time diff       | check time serv | 2        |  
 30044| urgent          | fix it asap     | 3        |      
 27188| urgent          | fix it asap     | 3        |      
 24323| urgent          | fix it asap     | 3        |      
 30047| test            | no details aval | 3        |
 30048| test2           | no details aval | 2        |      
 30049| test3           | no details aval | 2        |  

结果集包含id字段,但它包含8 rows

是否可以在每列上设置distinct,但id

2 个答案:

答案 0 :(得分:1)

首先,您的数据中存在一些不直观的内容,因此您可能会改进数据模型。

然后,根据您的信息,也许你可以使用这样的东西:

select distinct t1.id,
                t1.PARAMETER,
                t1.description,
                t1.severity
from task t1
where t1.topic_id=851
  and t1.id = (
               select max(t2.id) 
               from task t2 
               where t1.parameter = t2.parameter 
                 and t1.description = t2.description 
                 and t1.severity = t2.severity)
;

另一种方式:

select distinct parameter, description, severity, max(id)
from task
where topic_id=851
group by parameter, description, severity
;

答案 1 :(得分:0)

DISTINCT ON完全是这样做的:

  

SELECT DISTINCT从结果中删除重复的行。 SELECT DISTINCT ON会删除所有指定表达式上匹配的行。

     

http://www.postgresql.org/docs/9.3/static/sql-select.html

SELECT DISTINCT ON (parameter, description, severity)
       id, parameter, description, severity
FROM task
WHERE ...