简体   繁体   中英

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) . 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=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)

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