SQL SUM operation of multiple subqueries

后端 未结 6 857
清歌不尽
清歌不尽 2021-01-12 09:52

i have the following mysql database table designed,

ticket(id, code, cust_name);
passenger(id, ticket_id, name, age, gender, fare);
service(id, passenger_id,         


        
6条回答
  •  情深已故
    2021-01-12 10:44

    You can just join the three tables together, then you can do the SUMs directly without the subselect. You'll need to use GROUP BY to group by ticket.id if you want it per ticket.

    Something like:

    SELECT t.id, SUM(p.fare) AS total_far, SUM(s.cost) AS total_cost
    FROM 
        ticket t, passenger p, service s
    WHERE t.id = p.ticket_id AND s.passenger_id = p.id 
    GROUP BY t.id;
    

提交回复
热议问题