从不同的表中获取时子查询的错误

时间:2015-07-02 12:14:32

标签: php mysql sql

我在下面运行查询并出现错误

  

子查询返回多行

我已将所有子查询in替换为any=。但问题没有解决。

SELECT *
from UserPost
where UserId = UserId_Param
   or UserId = any (select UserId from UserPals
                    where PalUserId = UserId_Param and FriendStatus = 1)
   or UserId = any (select PalUserId from UserPals
                    where UserId = UserId_Param and FriendStatus = 1)
and privacy = 1
and PostId not in (select PostId from UserHidePost where UserId = UserId_Param)
and Committed = 1
and Trashed = 0 

union all

select *
from UserPost
where privacy = 2
  and PostId = any(select PostId from PostCategory
                   where PalCategoryId = any (select UserPalCategoryId
                                              from PalCategory
                                              where userId = UserId_Param
                                                 or PalUserId = UserId_Param))
  and PostId not in(select PostId from UserHidePost
                    where UserId = UserId_Param)
  and Committed = 1
  and (UserId = any (select UserId from UserPals
                     where PalUserId = UserId_Param and FriendStatus = 1)
       or (select PalUserId from UserPals
           where UserId = UserId_Param and FriendStatus = 1))
  and Trashed = 0
LIMIT lim_val OFFSET lim_offset;

2 个答案:

答案 0 :(得分:1)

可能导致此问题的唯一明显的(对我而言)子查询是:

 (select PalUserId from UserPals
       where UserId = UserId_Param and FriendStatus = 1)

也许你想要exists

exists (select PalUserId from UserPals
        where UserId = UserId_Param and FriendStatus = 1
       )

顺便说一句,混合= any ()in似乎有点奇怪。

答案 1 :(得分:1)

此子查询缺少任何子句:

SELECT *
from UserPost
where UserId = UserId_Param
   or UserId = any (select UserId from UserPals
                    where PalUserId = UserId_Param and FriendStatus = 1)
   or UserId = any (select PalUserId from UserPals
                    where UserId = UserId_Param and FriendStatus = 1)
and privacy = 1
and PostId not in (select PostId from UserHidePost where UserId = UserId_Param)
and Committed = 1
and Trashed = 0 

union all

select *
from UserPost
where privacy = 2
  and PostId = any(select PostId from PostCategory
                   where PalCategoryId = any (select UserPalCategoryId
                                              from PalCategory
                                              where userId = UserId_Param
                                                 or PalUserId = UserId_Param))
  and PostId not in(select PostId from UserHidePost
                    where UserId = UserId_Param)
  and Committed = 1
  and (UserId = any (select UserId from UserPals
                     where PalUserId = UserId_Param and FriendStatus = 1)
     ----THIS->  or (select PalUserId from UserPals
           where UserId = UserId_Param and FriendStatus = 1))-- <---
  and Trashed = 0
LIMIT lim_val OFFSET lim_offset;