简体   繁体   中英

Using the result of a sub-select in the WHERE clause in a MySQL query

SELECT
  *, (SELECT SUM(rating) FROM votes WHERE votes.postId = posts.id) AS rating
FROM posts
WHERE rating > 10

There are multiple entries in my table where the sum of the ratings in votes with the corresponding post ID is greater than 10, but this query is not returning any results. Why?

Here is the relevant portion of my database structure:

TABLE posts
 - id

TABLE votes
 - postId
 - rating

Any help would be greatly appreciated.

You need to name the subquery column, like this

SELECT * FROM (SELECT sum(rating) as rating_sum, * FROM posts) AS rating INNER JOIN posts on posts.id = rating.id WHERE rating.rating_sum>10

try this.

 SELECT posts.*, (select SUM(rating) as totalRating 
                    from votes 
                   where votes.postid = posts.id) as totalRating
 FROM   posts 
 WHERE  totalRating > 10 

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