通过每个选择中的两个不同列对两个选择进行联合的顺序

时间:2019-02-03 11:16:37

标签: php mysql sql

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

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  

2 个答案:

答案 0 :(得分:1)

考虑使用内部查询,前提是所有三列的数据类型相同, 和
, commentDate DESC子句中删除ORDER BY,因为commentDate也被认为是postDate

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

答案 1 :(得分:0)

这是您的查询:

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

没有ORDER BY,结果集将包含三列,分别为名称postIdpostContentpostDate。这些可以在ORDER BY中使用。实际上,commentDate将在结果集中重命名为postdate

因此,此ORDER BY将起作用:

ORDER BY postDate DESC

不过,我怀疑那是您真正想要的。如果我推测一下,我会发现以下有用:

SELECT p.postId, p.postDate, p.postContent, NULL as commentDate, NULL as commentContent
FROM posts p
UNION ALL
SELECT p.postId, p.postDate, c.commentId, c.commentContent, c.commentDate
FROM comments c JOIN
     posts p
     ON c.postId = p.postId
ORDER BY postDate DESC, postId DESC, commentDate DESC