我有三个表以一对多的关系连接起来:a+b->一对多,b+c->一对多。对于每个条目a,我想得到它的所有b条目和它们的两个连接的c条目 max(C.created)
以及 min(C.created)
答:
+-----+
| id |
+-----+
|0. |
+-----+
第二:
+---------------+
| 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
+--------------------------+
结果:
+--------------------------+
| A_id | C_id | created|
+--------------------------+
|0 | 3 | 2010
|0 | 5 | 2020
|0 | 6 | 2011
|0 | 7 | 2015
+--------------------------+
这就是我失败的尝试的样子,我只是不能让它像我想的那样工作:
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
2条答案
按热度按时间2lpgd9681#
你的数据看起来像
c
链接到b
,不是a
. 假设是这样,您可以使用窗口函数:pbwdgjma2#
您的查询应该是