首页 > 解决方案 > 通过每个选择中的两个不同列对具有两个选择的联合进行排序

问题描述

该查询非常简单,如下所示:

SELECT postId, postContent, postDate FROM posts UNION 
ALL SELECT commentId, commentContent, commentDate FROM comments 
ORDER BY postDate DESC, commentDate DESC

相反,得到有序的结果我得到一个 mysqli 警告mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, bool given

请帮忙。

php代码如下

$query = mysqli_query($conn, $query);
while($row = mysqli_fetch_assoc($query)) {
echo $row['postId'];
echo $row['postContent'];
echo $row['postDate'];
}

postId    postContent     postDate
-------------------------------------
1    |   sample post1    | 03-02-2019
-------------------------------------
2    |  sample post 2    | 04-02-2019    

这是帖子,这是评论

commentId    commentContent     commentDate
--------------------------------------------
1        |   sample comment1    | 03-02-2019
--------------------------------------------
2        |  sample comment2     | 04-02-2019  

标签: phpmysqlsql

解决方案


考虑使用内部查询,前提是所有三列都具有相同的数据类型,并从子句中
删除,因为也被认为是。, commentDate DESCORDER BYcommentDatepostDate

SELECT q.*
  FROM
  ( 
   SELECT postId, postContent, postDate FROM posts
   UNION ALL
   SELECT commentId, commentContent, commentDate FROM comments 
   ) q
 ORDER BY postDate DESC

推荐阅读