I have three tables connected in a following one-to-many relationships: A+B -> one-to-many, B+C -> one-to-many. For every entry AI want to get all its B entries and two of their connected C entries representing max(C.created)
and min(C.created)
A:
+-----+
| id |
+-----+
|0. |
+-----+
B:
+---------------+
| id | A_id |
+---------------+
|1. | 0. |
|2. | 0. |
+---------------+
C:
+--------------------------+
| id | B_id | created |
+--------------------------+
|3 | 1 | 2010
|4 | 1 | 2015
|5 | 1 | 2020
|6 | 2 | 2011
|7 | 2 | 2015
|8 | 2 | 2014
+--------------------------+
result:
+--------------------------+
| A_id | C_id | created|
+--------------------------+
|0 | 3 | 2010
|0 | 5 | 2020
|0 | 6 | 2011
|0 | 7 | 2015
+--------------------------+
This is how my failed attempts looks like, I just cannot make it work as I'd like to:
select A.id, C.id, C.created
from A
join B on (A.id = B.A_id)
join (select *
from C
where C.created = (select min(created) from C) or
C.created = (select max(created) from C)
) as foo
on B.id = foo.B_id
Your data looks like c
has a link to b
, not a
. Assuming this is the case, you can use window functions:
select a.*, b.*, c.*
from a join
b
on b.a_id = a.id join
(select c.*,
row_number() over (partition by c.b_id order by c.created) as seqnum_asc,
row_number() over (partition by c.b_id order by c.created desc) as seqnum_desc
from c
) c
on b.id = c.b_id and
1 in (seqnum_asc, seqnum_desc);
your query should be
select A.id, foo.id, foo.created
from A
join B on (A.id = B.A_id)
join (select *
from C
where C.created = (select min(created) from C as C1 where C.B_id=C1.B_id) or
C.created = (select max(created) from C as C1 where C.B_id=C1.B_id)
) as foo
on B.id = foo.B_id
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.