【问题标题】:MySql throws error Subquery returns more than 1 rowMySql 抛出错误子查询返回超过 1 行
【发布时间】:2015-10-10 22:51:49
【问题描述】:

我想从出现错误“子查询返回超过 1 行”的 3 个表中检索值。

我的概念是检索我必须从 ttpostvotes 表中计算每个帖子的投票总和的所有帖子,如果提供的用户 ID 被投票给该帖子,那么它将显示帖子计数,如 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

ttpostvotes

treply

【问题讨论】:

    标签: mysql


    【解决方案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);
    

    【讨论】:

      猜你喜欢
      • 2023-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-13
      相关资源
      最近更新 更多