简体   繁体   中英

How to inner join 2 table and sum the third

i have a problem with a mysql query with 3 tables. I have to print the id of the users (on users table) the time of request present in the book_request table and sum the book buyed on other table

select 
    U.id AS ID, 
    B.time_request AS Time,
    (select SUM(volume) from book_buyed O where O.user_id = 62) as BookBuyed 
 from book_request B 
 inner join users U on B.id_cliente = U.id

with this code it's works but i have to select manually the id

if i use this code

select 
    U.id AS ID, 
    B.time_request AS Time,
    (select SUM(volume) from book_buyed O where O.user_id = U.id) as BookBuyed 
 from book_request B 
 inner join users U on B.id_cliente = U.id

if i use this code the BookBuyed column result everytime null

I've always tried to avoid select queries embedded in another query's select list:

select 
  U.id AS ID, 
  B.time_request AS Time,
  Bookbuyed.sumvol
from 
  book_request B 
  inner join users U on B.id_cliente = U.id
  inner join (select user_id, SUM(volume) sumvol from book_buyed group by user_id) as BookBuyed on u.id = bookbuyed.user_id

Doing them in the join area helps me better segment them into "a block of data that is joined to other blocks of data" mentally; here you can conceive that the sum volume is worked out first and then the resulting data from this sub query is fed into the other joins as if it were a table

You can consider using left join with group by clause

select 
      U.id AS ID, 
      B.time_request AS Time,
      sum(volume) as BookBuyed 
 from users U 
 left join book_request B on B.id_cliente = U.id
 left join book_buyed O on O.user_id = U.id
group by U.id, B.time_request;

rather than using a subquery.

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM