2015-10-10 133 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);