php - 通过每个选择中的两个不同列对具有两个选择的联合进行排序
问题描述
该查询非常简单,如下所示:
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
解决方案
考虑使用内部查询,前提是所有三列都具有相同的数据类型,并从子句中
删除,因为也被认为是。, 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
推荐阅读
- c - 如何在c中的文件上写入文本?
- mongodb - $lookup 查找由 id 匹配的对象数组
- google-analytics - Google Analytics 4 / 每个事件具有多个值的自定义维度
- android - Xamarin.Android:在 Android 10+ 中使用 Intents 打开 Excel 文档失败
- linux - 如何在 Windows 终端中模拟一些 Putty 设置
- file-upload - 上传大文件时,fastapi 抛出 400 错误请求
- c# - 在 WPF 应用程序中使用 Styles 或 DataTemplate 更改控件子对象的属性
- javascript - 如何从现有对象初始化打字稿类?
- ios - 如何在自定义 UISearchBar 子类中使用委托方法
- google-sheets - 谷歌工作表获取 api 响应限制