Search code examples
mysqlsqlsuminner-join

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


Solution

  • 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