开发者

Complex 3 way SQL join (where table 3 has to join table 2 before joining table 1)

开发者 https://www.devze.com 2023-02-17 22:31 出处:网络
I have three existing SQL tables we will call \"teams\", \"miles\", and \"riders\". Leaving out the fluff, their structure looks li开发者_如何学JAVAke this:

I have three existing SQL tables we will call "teams", "miles", and "riders". Leaving out the fluff, their structure looks li开发者_如何学JAVAke this:

Table: teams
------------+-------------+---------+
| team_name | captains_id | team_id |
------------+-------------+---------+
| superbads | 11          | 1       |
| superflys | 12          | 2       |
------------+-------------+---------+

Table: riders
--------------+-----------+----------+
| rider_name  | team_id   | rider_id |
--------------+-----------+----------+
| donatello   | 1         | 10       |
| leonardo    | 1         | 11       |
| michelangelo| 2         | 12       |
| raphael     | 2         | 13       |
--------------+-----------+----------+

Table: miles
--------------+-----------+----------+
| rider_id    | miles     | id       |
--------------+-----------+----------+
| 10          | 100       | 1        |
| 10          | 62        | 2        |
| 11          | 110       | 3        |
| 11          | 100       | 4        |
| 12          | 8         | 5        |
| 12          | 22        | 6        |
| 13          | 29        | 7        |
| 13          | 2         | 8        |
--------------+-----------+----------+

I need to return a list of teams with total miles generated by that team (I also need to return the team captain's name, but that's a bit easier). The difficulty is that I need to join miles on riders, sum the "miles" field, and then join that on teams somehow.

Changing the table structure is pretty much out, as this is an existing application. This is a LAMP environment, so manipulating PHP arrays after the query is an option if needed.


This should do it:

select t.team_id, t.team_name, t.captains_id, sum(m.miles) as total_miles
from teams t
inner join riders r on r.team_id = t.team_id
inner join miles m on m.rider_id = r.rider_id
group by t.team_id, t.team_name, t.captains_id
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号