MySql抛出错误子查询返回超过1行

时间:2015-10-10 13:51:53

标签: mysql

我想从3表中检索值,我收到错误“子查询返回超过1行”。

我的概念是检索所有帖子,其中我必须计算ttpostvotes表中关于每个帖子的投票总和,如果提供了userid被投票给该帖子,那么它将显示帖子计数如1或-1

我的查询如下:

SELECT r.PostId, r.`Post`,r.PostTime, coalesce(x.Votes, 0) as Votes , 
(Select Votes From `ttpostvotes` where UserId=30 and x.PostId=r.PostId ) as IsUservoted, 
(Select Count(*) From ttreply where PostId=r.PostId ) AS ReplyCount FROM `ttpost` r 
left join ( SELECT PostId, sum(Votes) as Votes FROM `ttpostvotes` GROUP BY PostId ) x ON
 x.PostId = r.PostId WHERE r.OffensiveCount<3 and r.SpamCount<5 and r.OtherCount<7 and r.`PeekId`=101 ORDER BY `r`.`PostTime` DESC

3个表格如下: ttpost

ttpost table structure

ttpostvotes

ttpostvotes

ttreply

ttreply

1 个答案:

答案 0 :(得分:1)

这是您的select

SELECT r.PostId, r.`Post`,r.PostTime, coalesce(x.Votes, 0) as Votes, 
       (Select Votes From `ttpostvotes` where UserId = 30 and x.PostId = r.PostId
       ) as IsUservoted, 
       (Select Count(*) From ttreply where PostId=r.PostId ) AS ReplyCount

第一个子查询没有聚合,所以我猜一个用户可以为一个帖子多次投票。这将修复语法错误:

SELECT r.PostId, r.`Post`,r.PostTime, coalesce(x.Votes, 0) as Votes, 
       (Select SUM(Votes) From `ttpostvotes` where UserId = 30 and x.PostId = r.PostId
       ) as IsUservoted, 
       (Select Count(*) From ttreply where PostId = r.PostId ) AS ReplyCount

它是否能满足您的需求是一个不同的问题。

注意:如果您希望原始查询有效,则应在ttpostvotes上定义唯一约束/索引:

create unique index unq_ttpostvotes_userid_postid on ttpostvotes(userid, postid);