2015-10-10 100 views
0

我想从3表中检索值,我收到错误“子查询返回多于1行”。MySql抛出错误子查询返回多于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

这是您的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);