我有3个表:
表:
id name
2 A
3 B
表:b
id a b
3 2 Asd Ter Gsdt
4 2 Gsd Gsdt Gsda
5 2 Asd Gsd
6 3 Uty Kggs
7 3 Tyud Hffddf
表:c
id a b
6 3 d
7 3 a
8 3 g
9 3 h
10 4 j
11 5 y
12 5 s
13 6 d
14 6 h
预期输出:
a b c d
A 2019-04-06 3 a
B 2019-04-06 6 b
我不确定如何从这个开始,如何?
这个查询完成了任务,但是总是有一个关于速度和性能的问题。
select a.name,
(select c_date from c
join b on (c.b_id = b.id)
where b.a = a.id order by c_date desc limit 1) last_c_date,
popular.b_id,
(select photos->0 from b where id = popular.b_id) photo
from a
join (
select distinct on (a)
b.id b_id, a from b
join c on (b.id = c.b_id)
group by b.id, a
order by a, count(*) desc, b.id
) popular on (popular.a = a.id)
order by a.name
如果在一个区域中有2个同样流行的b对象,查询取id较小的这个。
如果没有b对象的条目在c中,那么subquery for photo可以被coalesce包围(但现在它也应该与null
value一起工作)。