简体   繁体   English

如何在一次连接三个表时求和一列

[英]how can I sum a column while joining three tables at once

I believe there is a good way to do. 我相信有一个很好的方法。 I searched and tried but could not find. 我搜索并尝试,但找不到。 I want to join three tables like this (or a better way, please suggest) 我想加入三个这样的表格(或者更好的方法,请提出建议)

SELECT listing.*, users.username, review.rNumber 
     FROM listing, users,review 
WHERE users.uid=listing.cuid and listing.lid=review.lID

But I don't want the review.rNumber I want to get sum of it like sum(rNumber) . 但是我不想要review.rNumber我想要像sum(rNumber)这样得到它的sum(rNumber) Because one listing can have many reviews.. Thank you.. 因为一个清单可以有很多评论..谢谢..

Here is what I want to achieve with this query 这是我要通过此查询实现的

  1. All the values from listing table. 列表中的所有值。
  2. only username from users table 用户表中的唯一用户名
  3. sum of reviews from review table 评论表中评论的总和

The relation is 关系是

  • users.uid=listing.cuid and listing.lid=review.lID or users.uid = listing.cuid和listing.lid = review.lID或
  • users.uid=listing.cuid=review.sellerID users.uid = listing.cuid = review.sellerID

Please let me know if I need to add table.. Thanks :) 请让我知道是否需要添加表格。。谢谢:)

you can get the sum for user with proper group by but for join with all the listing result you could use a dinamic join 您可以为具有适当分组的用户获得总和,但要与所有列表结果合并,可以使用动态合并

SELECT listing.*, t.username, t.sum_rNumber
fFROM listing
INNER JOIN users   ON users.uid=listing.cuid
INNER JOIN review ON listing.lid=review.lID
INNER JOIN (
      SELECT  users.username as username,  sum( review.rNumber) sum_rNumber
      FROM listing
      INNER JOIN users   ON users.uid=listing.cuid
      INNER JOIN review ON listing.lid=review.lID
      GROUP BY users.username
    ) t on users.username = t.username

(and is more readable the explicit join sintax) (并且更可读的显式连接正弦)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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