выбрать сообщения с комментариями с наибольшим количеством лайков / антипатий по xxx desc

0

У меня есть две таблицы, posts и comments. В posts столбцов таблицы являются: id, body, user_id, likes, dislikes, time. В столбцах таблицы comments: id, body, post_id, user_id, likes, dislikes, time.

Давайте рассмотрим сценарий с двумя сообщениями (A и B). Post-A имеет 1 комментарий с 10-симпатичными и 2-антипатиями, Post-B имеет 1 комментарий с 5-симпатичными и 12-антипатиями.

При заказе сообщений через category конечных точек API, как мне выполнить ORDER BY comment.likes/dislikes DESC которая начинается с Post-B, если запрос является most disliked комментарием. Или начните с Post-A, если запрос для most liked комментария.

Вот как выглядит мой текущий запрос, который заказывается по количеству комментариев для комментариев для любого запроса комментария. Заметьте, что я не выбираю из таблицы comments поскольку комментарии загружаются для каждого идентификатора сообщения после получения сообщений.

<?

if (isset($_GET['ordertags'])) {
  //post tags e.g general/work/school etc
  $orderTags = $_GET['ordertags'];
}else {
  $orderTags = "alltags";
}

if (isset($_GET['orderreactions'])) {
  //post reactions, e.g date time/ most post-likes/dislikes/comments & comment-likes/dislikes etc
  $orderReactions = $_GET['orderreactions'];
}else {
  $orderReactions = "pdt";
}

//declare vars
$orderBy = "";
//get start offset to load the first 10 results
$start = (int)$_GET['start'];

switch ($orderReactions) {
  case "pdt":
    $orderBy = "ORDER BY posts.posted_at";
    break;
  case "mlp":
    $orderBy = "AND posts.likes != 0 ORDER BY posts.likes";
    break;
  case "mdp":
    $orderBy = "AND posts.dislikes != 0 ORDER BY posts.dislikes";
    break;
  case "mcp":
    $orderBy = "AND posts.comments != 0 ORDER BY posts.comments";
    break;
  case "mlc":
    $orderBy = "AND posts.comments != 0 ORDER BY posts.comments";
    break;
  case "mdc":
    $orderBy = "AND posts.comments != 0 ORDER BY posts.comments";
    break;
  default:
    $orderBy = "ORDER BY posts.posted_at";
    break;
}

//posts from users 
if ($orderTags == "alltags") {

  $followingposts = $db->query('SELECT posts.id, posts.body, posts.posted_at, posts.likes, posts.dislikes, posts.tags, users.'username', users.'profileimg' FROM users, posts
    WHERE users.id = posts.user_id
    '.$orderBy.' DESC LIMIT 10 OFFSET '.$start.';');

}else {

  $followingposts = $db->query('SELECT posts.id, posts.body, posts.posted_at, posts.likes, posts.dislikes, posts.tags, users.'username', users.'profileimg' FROM users, posts
    WHERE users.id = posts.user_id
    AND tags = :tag
    '.$orderBy.' DESC LIMIT 10 OFFSET '.$start.';', array(':tag'=>$orderTags));

}


?>

Это то, что выглядит моя конечная точка comments, которая извлекает наиболее понравившиеся/нелюбимые комментарии без поблама.

<?

if (isset($_GET['action'])) {
  //comment action request i.e most liked/disliked/regular i.e postDate
  $action = $_GET['action'];
}else {
  $action = "reg";
}

//declare vars
$orderBy = "";

switch ($action) {
    case "mdc":
        $orderBy = "ORDER BY comments.dislikes DESC";
        break;
    case "mlc":
        $orderBy = "ORDER BY comments.likes DESC";
        break;
    case "reg":
        $orderBy = "ORDER BY comments.posted_at ASC";
        break;
    default:
        $orderBy = "ORDER BY comments.posted_at ASC";
        break;
}

//fetch comments from db
$comments = $db->query('SELECT comments.id, comments.comment, comments.post_id, comments.posted_at, comments.likes, comments.dislikes, users.username, users.profileimg FROM comments, users WHERE comments.post_id = :postid AND comments.user_id = users.id '.$orderBy.';', array(':postid'=>$_GET['postid']));   


?>

Таким образом, проблема заключается в том, как выбрать должности с наивысшими любимыми/нелюбимыми комментариями в инструкции ORDER BY DESC при этом все же исключая сообщения с комментариями с 0 симпатиями/антипатиями. Благодарю.

  • 1
    Учитывая то, как вы структурировали свои данные, любые «нравится» или «не нравится» будут постоянными, потому что они связаны с постами и комментариями, а не с тем, кому нравится и не нравится. Как проверить, понравился ли кому-то пост или комментарий? Что касается вашего вопроса: аналогично вашему $orderBy вы можете добавить условие $where в ваших случаях переключения. В некоторых случаях это будут comments.likes != 0 или comments.dislikes != 0 а в других просто пустая строка.
Теги:

2 ответа

0
Лучший ответ

Добавил INNER JOIN все работает нормально

<?

switch ($orderReactions) {
  case "pdt":
    if ($orderTags == "alltags") {

      $orderBy = "WHERE users.id = posts.user_id ORDER BY posts.posted_at";
    }else {
      $orderBy = "WHERE users.id = posts.user_id AND tags=:tag ORDER BY posts.posted_at";
    }
    
    break;
  case "mlp":
    if ($orderTags == "alltags") {

      $orderBy = "WHERE users.id = posts.user_id AND posts.likes != 0 ORDER BY posts.likes";
    }else {
      $orderBy = "WHERE users.id = posts.user_id AND tags=:tag AND posts.likes != 0 ORDER BY posts.likes";
    }
    
    break;
  case "mdp":
    if ($orderTags == "alltags") {

      $orderBy = "WHERE users.id = posts.user_id AND posts.dislikes != 0 ORDER BY posts.dislikes";
    }else {
      $orderBy = "WHERE users.id = posts.user_id AND tags=:tag AND posts.dislikes != 0 ORDER BY posts.dislikes";
    }
    
    break;
  case "mcp":
    if ($orderTags == "alltags") {

      $orderBy = "WHERE users.id = posts.user_id AND posts.comments != 0 ORDER BY posts.comments";
    }else {
      $orderBy = "WHERE users.id = posts.user_id AND tags=:tag AND posts.comments != 0 ORDER BY posts.comments";
    }
    
    break;
  case "mlc":
    if ($orderTags == "alltags") {

      $orderBy = "INNER JOIN comments ON comments.post_id = posts.id WHERE posts.user_id = users.id AND posts.comments != 0 AND comments.likes != 0 GROUP BY post_id ORDER BY comments.likes";
    }else {
      $orderBy = "INNER JOIN comments ON comments.post_id = posts.id WHERE posts.user_id = users.id AND tags=:tag AND posts.comments != 0 AND comments.likes != 0 GROUP BY post_id ORDER BY comments.likes";
    }
    
    break;
  case "mdc":
    if ($orderTags == "alltags") {

      $orderBy = "INNER JOIN comments ON comments.post_id = posts.id WHERE posts.user_id = users.id AND posts.comments != 0 AND comments.dislikes != 0 GROUP BY post_id ORDER BY comments.dislikes";
    }else {
      $orderBy = "INNER JOIN comments ON comments.post_id = posts.id WHERE posts.user_id = users.id AND tags=:tag AND posts.comments != 0 AND comments.dislikes != 0 GROUP BY post_id ORDER BY comments.dislikes";
    }
    
    break;
  default:
    if ($orderTags == "alltags") {

      $orderBy = "WHERE users.id = posts.user_id ORDER BY posts.posted_at";
    }else {
      $orderBy = "WHERE users.id = posts.user_id AND tags=:tag ORDER BY posts.posted_at";
    }
    break;
}

//posts from users followed by current logged in user + logged in user
if ($orderTags == "alltags") {

  $followingposts = $db->query('SELECT posts.id, posts.body, posts.posted_at, posts.likes, posts.dislikes, posts.tags, posts.user_id, users.'username', users.'profileimg' FROM users, posts
    '.$orderBy.' DESC LIMIT 10 OFFSET '.$start.';');
  
}else {

  $followingposts = $db->query('SELECT posts.id, posts.body, posts.posted_at, posts.likes, posts.dislikes, posts.tags, posts.user_id, users.'username', users.'profileimg' FROM users, posts
    '.$orderBy.' DESC LIMIT 10 OFFSET '.$start.';', array(':tag'=>$orderTags));

}
?>
1

Вы можете использовать JOINS для исключения сообщений с комментариями 0 нравится/не нравится (SELECT Posts. * FROM Posts JOIN Комментарии ON Posts.id = Comments.post_id WHERE Комментарии.likes> 0 И Комментарии.dislikes> 0)

Ещё вопросы

Сообщество Overcoder
Наверх
Меню