one-to-many query selecting all parents and single top child for each parent

后端 未结 5 1801
别那么骄傲
别那么骄傲 2020-12-24 07:31

There are two SQL tables:

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

Childs
+--+-----         


        
5条回答
  •  醉话见心
    2020-12-24 08:25

    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
    

提交回复
热议问题