查询非常简单,如下所示:
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
答案 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
,结果集将包含三列,分别为名称postId
,postContent
和postDate
。这些可以在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