我目前正在开发一个社交媒体应用,其中包括用户(您可以将他们添加为 friend )和帖子(文本,图片等...)
我想向用户显示5条最新帖子,与用户输入应用程序时用户的帖子和用户的 friend 的帖子相比。
我知道这不是实现这一目标的最明智的方法,但到目前为止,我做到了。 查询仅返回一则帖子,而帖子数量更多,并且甚至不是最新的也不是最旧的。我认为问题出在“OR”子句中。
我得到了用户 friend 的所有帮助,并用“OR”子句一一放入WHERE子句中。
//CURRENT FRIENDS
$sql = 'SELECT current AS currents FROM friends WHERE sno = :sno';
$query = $this -> conn -> prepare($sql);
$query -> execute(array(':sno' => $usersSno));
$friends = $query -> fetchObject() -> currents;
//SELECT 5 NEWEST POST
$sql = 'SELECT operationId FROM posts WHERE operationId = :operationId';
$array = array(':operationId' => $usersSno);
if(isset($friends)) {
$ids = explode(",", $friends);
for($i = 0; $i < count($ids); $i++) {
$sql = $sql.' OR operationId = :operationId'.$i;
$array[':operationId'.$i] = $ids[$i];
}
}
if($from == null)
$sql = $sql.' ORDER BY operationId DESC LIMIT 5';
else {
$sql = $sql.' AND operationId < :from ORDER BY operationId DESC LIMIT 5';
$array[':from'] = $from;
}
$query = $this -> conn -> prepare($sql);
$query -> execute($array);
$result = $query -> fetchAll(PDO::FETCH_ASSOC);
用户的sno为1,用户有两个 friend ,他们的sno为2和75。
echo $ sql;
SELECT operationId FROM posts WHERE operationId = :operationId OR operationId = :operationId0 OR operationId = :operationId1 ORDER BY operationId DESC LIMIT 5
print_r($ array);
Array
(
[:operationId] => 1
[:operationId0] => 2
[:operationId1] => 75
)
最佳答案
在获得赏金后立即意识到自己的错误,我感到很愚蠢。我应该使用WHERE sno
(因为我一直在从用户ID [sno]获取帖子)而不是WHERE operationId
中的$sql
因此echo $sql;
类似于:
SELECT operationId FROM posts WHERE sno = :sno OR sno = :sno0 OR sno = :sno1 ORDER BY operationId DESC LIMIT 5
而
print_r($array)
是:Array
(
[:sno] => 1
[:sno0] => 2
[:sno1] => 75
)
至少我很乐意解决这个问题,甚至自己解决这个问题:)
1-比较日期字符串和后的operationId
我正在比较帖子及其日期(您也可以将其与post的operationId进行比较),以查看哪个是最新的。但是在代码中,我将operationId与
$from
变量(这是一个日期字符串)进行了比较。这样的最终代码;
$sql = $sql.') AND createdAt < :from ORDER BY operationId DESC LIMIT 5';
2-OR子句应与AND子句用括号分隔。
括号的开始
$sql = 'SELECT operationId FROM posts WHERE (sno= :sno';
括号的结尾
if($from == null)
$sql = $sql.') ORDER BY operationId DESC LIMIT 5';
else {
$sql = $sql.') AND createdAt < :from ORDER BY operationId DESC LIMIT 5';
$array[':from'] = $from;
}
关于php - 获取新闻源(社交媒体),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50441118/