简体   繁体   English

在MySQL查询的WHERE子句中使用子选择的结果

[英]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. 我的表格中有多个条目,其中具有相应帖子ID的投票的评分总和大于10,但是此查询未返回任何结果。 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 SELECT * FROM(选择sum(rating)为rating_sum,* FROM帖子)AS评分INNER JOIN帖子中的帖子。id= rating.id WHERE评分。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 

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

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