如何内部联接2表并求和第三

时间:2019-06-29 17:55:31

标签: mysql sql sum inner-join

我对3个表的mysql查询有问题。 我必须在book_request表中打印出请求的时间(在users表上)的用户ID,并汇总在其他表上购买的书

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

使用此代码可以正常工作,但我必须手动选择ID

如果我使用此代码

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

如果我使用此代码,则每次null时BookBuyed列结果

2 个答案:

答案 0 :(得分:0)

我一直试图避免嵌入到另一个查询的选择列表中的选择查询:

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

在连接区域中进行操作有助于从心理上更好地将它们划分为“连接到其他数据块的数据块”;在这里,您可以设想首先计算出总和,然后将该子查询的结果数据馈送到其他联接中,就像表一样。

答案 1 :(得分:0)

您可以考虑将left joingroup by子句一起使用

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;

而不是使用子查询。

Demo