gpt4 book ai didi

mysql - 如何按表中的两个相关值排序

转载 作者:搜寻专家 更新时间:2023-10-30 20:36:36 27 4
gpt4 key购买 nike

在 MySQL 数据库中我有一个表:

+----+---------+-------------------+------------------+-------------------+  
| id | file_id | file_name | is_complementary | complementary_for |
+----+---------+-------------------+------------------+-------------------+
| 55 | 52 | photo.png | 0 | NULL |
| 56 | 53 | photo_edit.png | 1 | 52 |
| 57 | 54 | card.png | 0 | NULL |
| 58 | 55 | card_edit.png | 1 | 54 |
| 59 | 56 | photo_edit_2.png | 1 | 52 |
+----+---------+-------------------+------------------+-------------------+

表中记录了“原始”文件 (file_id) 及其编辑后的副本(“补充文件”)。如果文件是原始的 is_complementary 则该文件的值为 0,如果不是原始文件 is_complementary 则值为 1complementary_for 值表示它指的是哪个file_id

如果显示原始文件,如何对该表进行排序,其后的行是显示的原始文件的补充文件?我的目标是获得这样的结果:

+----+---------+-------------------+------------------+-------------------+ 
| id | file_id | file_name | is_complementary | complementary_for |
+----+---------+-------------------+------------------+-------------------+
| 55 | 52 | photo.png | 0 | NULL |
| 56 | 53 | photo_edit.png | 1 | 52 |
| 59 | 56 | photo_edit_2.png | 1 | 52 |
| 57 | 54 | card.png | 0 | NULL |
| 58 | 55 | card_edit.png | 1 | 54 |
+----+---------+-------------------+------------------+-------------------+

最佳答案

你可以试试:

 SELECT *
FROM <put table name here>
ORDER BY IF(is_complimentary = 0, file_id, complimentary_for), is_complimentary

第一个排序标准使用原始文件的ID;原始文件及其所有补充文件在排序结果中彼此相邻。第二个标准将原始文件放在其补充文件之前。您可以添加 file_id 以获得按创建顺序(或其他标准,如 file_name)排序的赠送文件。

但是,请注意这种排序不能使用索引并且在大型表上速度很慢。

关于mysql - 如何按表中的两个相关值排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36926318/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com