低于操作员给出奇怪的结果

时间:2018-06-12 11:09:52

标签: php mysql

所以我有这个查询将几个表连接在一起并返回数据

SELECT * FROM userposts up
INNER JOIN userpostmeta upm
ON up.up_postID = upm.upm_postID
INNER JOIN userbasicprofile ubp
ON up.up_userID = ubp.ubp_userID
WHERE up.up_userID = :self OR up.up_userID IN (SELECT ufs_userID2 FROM userfriends where ufs_userID1 = :u)
AND
up.up_indexid < $startIndex AND up.up_indexid > 0
ORDER BY up.up_indexid DESC
LIMIT $limit

userposts有一个名为'up_indexid`的列,自动增量

问题,当我为支持31发送$startIndex的值时,会显示indexid 31以下的帖子,但也会显示其上方的帖子。

为什么会这样?我尝试了多个断点,但似乎没有任何解决方案。

3 个答案:

答案 0 :(得分:0)

原因与<无关,原因是你的mysql查询中有OR

SELECT * FROM userposts up
INNER JOIN userpostmeta upm
ON up.up_postID = upm.upm_postID
INNER JOIN userbasicprofile ubp
ON up.up_userID = ubp.ubp_userID
WHERE up.up_userID = :self 
OR up.up_userID #OR makes things unexpected
  IN (SELECT ufs_userID2 FROM userfriends where ufs_userID1 = :u) 
AND
up.up_indexid < $startIndex AND up.up_indexid > 0
ORDER BY up.up_indexid DESC
LIMIT $limit

答案 1 :(得分:0)

尝试这样做:

'SELECT * FROM userposts up
INNER JOIN userpostmeta upm
ON up.up_postID = upm.upm_postID
INNER JOIN userbasicprofile ubp
ON up.up_userID = ubp.ubp_userID
WHERE up.up_userID = :self OR up.up_userID IN (SELECT ufs_userID2 FROM userfriends where ufs_userID1 = :u)
AND
up.up_indexid < ' . intval($startIndex) . ' AND up.up_indexid > 0
ORDER BY up.up_indexid DESC
LIMIT ' . intval($limit)

我注意到你正在使用Binding和in-string变量,为什么不绑定startIndex和limit呢? 另外,你可能想看一下偏移,在你的情况下可能是更好的解决方案,比如LIMIT 100,10(从第10个条目开始的100个条目)

答案 2 :(得分:0)

根据https://dev.mysql.com/doc/refman/8.0/en/operator-precedence.html OR的优先级低于AND,因此您的WHERE子句被解释为:

WHERE up.up_userID = :self OR (up.up_userID IN (SELECT ufs_userID2 FROM userfriends where ufs_userID1 = :u)
AND
up.up_indexid < $startIndex AND up.up_indexid > 0)
ORDER BY up.up_indexid DESC
LIMIT $limit

我想你想要的是以下内容:

WHERE (up.up_userID = :self OR up.up_userID IN (SELECT ufs_userID2 FROM userfriends where ufs_userID1 = :u))
AND
up.up_indexid < $startIndex AND up.up_indexid > 0
ORDER BY up.up_indexid DESC
LIMIT $limit