admin

一对多查询,选择所有父母和每个父母的独生子女

sql

有两个SQL表:

Parents:
+--+---------+
|id|   text  |
+--+---------+
| 1|  Blah   |
| 2|  Blah2  |
| 3|  Blah3  |
+--+---------+

Childs
+--+------+-------+
|id|parent|feature|
+--+------+-------+
| 1|   1  |  123  |
| 2|   1  |   35  |
| 3|   2  |   15  |
+--+------+-------+

我想用单个查询从Parents表中选择每一行,并从Childs表中为具有关系“ parent”-“ id”值和最大“
feature”列值的每一行选择一个查询。在此示例中,结果应为:

+----+------+----+--------+---------+
|p.id|p.text|c.id|c.parent|c.feature|
+----+------+----+--------+---------+
|  1 | Blah |  1 |    1   |    123  |
|  2 | Blah2|  3 |    2   |    15   |
|  3 | Blah3|null|   null |   null  |
+----+------+----+--------+---------+

其中p =父表,c =子表

我试图离开外部联接和GROUP BY,但是MSSQL Express告诉我,使用GROUP
BY进行查询需要在每个非Groupped字段上使用聚合函数。而且我不想将它们全部分组,而是选择第一行(具有自定义顺序)。

我完全没有主意…


阅读 195

收藏
2021-05-10

共1个答案

admin

select p.id, p.text, c.id, c.parent, c.feature
from Parents p
left join (select c1.id, c1.parent, c1.feature
             from Childs c1
             join (select p1.id, max(c2.feature) maxFeature
                     from Parents p1
                left join Childs c2 on p1.id = c2.parent
            group by p1.id) cf on c1.parent = cf.id 
                              and c1.feature = cf.maxFeature) c
on p.id = c.parent
2021-05-10