离开加入和分组

时间:2017-01-15 07:05:10

标签: sql postgresql group-by left-join

我有下面两个表,我想在任务表中列出位置行基,并且不要复制location.id,也要按任务表中的列顺序。

我不确定如何解决它使用group by或其他方法?
(我之前也检查过明显,但它限制选择特定的列,似乎不是我想要的..)
怎么解决?

location
id | status | ...
1  | ...
2  | ...

id SERIAL NOT NULL

task
id | location_id | create_date | start_date | ...
1  | 1           | ...
2  | 1           | ...
3  | 2           | ...

id SERIAL NOT NULL
location_id integer DEFAULT NULL
create_date timestamp without time zone NOT NULL  
start_date date NOT NULL

需要输出结果

location  order by task.create_date
id | ...
1  | ...
2  | ...

查询

我添加了选择t.location_id它可以计数,但我在选择行中仍有问题

计数工作

SELECT count(l.*)
   AS total_row_count 
   FROM location l
         LEFT JOIN (
           SELECT t.location_id
           FROM task t
           GROUP BY t.location_id
           ) t ON t.location_id  = l.id
        WHERE l.status = ANY($1::int[])

选择

SELECT
  l.* 
  FROM location l 
        LEFT JOIN (
          SELECT t.location_id, t.create_date
          FROM task t
          GROUP BY t.location_id
          ) t ON t.location_id  = l.id
       WHERE l.status = ANY($1::int[]) 
       ORDER BY t.create_date desc NULLS LAST, 
       l.name asc NULLS LAST, l.id desc NULLS LAST OFFSET $2 LIMIT $3

错误:

  

列“t.create_date”必须出现在GROUP BY子句中或使用   在聚合函数SELECT t.create_date,t.location_id

2 个答案:

答案 0 :(得分:1)

您可以简单地执行左连接以获取任务表中的location_id和相应的行数,如下所示:

select l.id, count(t.location_id) times
from location l
left join task t
on l.id = t.location_id
group by l.id
order by max(t.create_date) desc;

如果location_id在您的位置表中是唯一的(可能是PK),并且您想要从该表中选择所有或多个列,则可以将它们放在查询的select和group by子句中。

答案 1 :(得分:1)

如果您想列出表location的记录和列,那么您可以使用exists,如下所示:

select * from location l where exists (select 1 from task where location_id=l.id)

您可以找到演示here