如何通过两个表中的字段交叉/存在来排序数据顺序?
序列存在于文件夹表和文件表中,如何对它们进行排序
查询
SELECT * FROM folder fo
LEFT JOIN file fi ON fi.parent_folder_id = fo.id
WHERE fo.parent_folder_id = $1 AND fi.parent_folder_id = $1
ORDER BY fo.sequence fi.sequence ?? ; << my problem
[1]
数据示例
folder
id | sequence | parent_folder_id | name
1 | 0 | | root
2 | 0 | 1 |
3 | 2 | 1 |
file
id | sequence | parent_folder_id |
1 | 1 | 1 |
输出
folder(id:1, sequence:0 name:root)
folder(id:2, sequence:0)
file(id:1, sequence:1)
folder(id:3 sequence:2)
答案 0 :(得分:2)
如果要列出给定文件夹第一级下的所有文件和文件夹,我建议您使用UNION ALL并获取文件列表和文件夹列表:
(
SELECT 'folder' AS type, fo.id, fo.sequence, fo.name
FROM folder fo
WHERE fo.parent_folder_id = 1
)
UNION ALL
(
SELECT 'file' AS type, fi.id, fi.sequence, NULL
FROM file fi
WHERE fi.parent_folder_id = 1
)
ORDER BY sequence;
你在文件表中没有名字很奇怪,但我认为这可能只是对问题的过度简化。如果您还想在列表中包含父文件夹,我只需将其添加为另一个UNION ALL子查询,其中包含固定的较低顺序:
(
SELECT 'folder' AS type, fo.id, -1 AS sequence, fo.name
FROM folder fo
WHERE fo.id = 1
)
UNION ALL
(
SELECT 'folder' AS type, fo.id, fo.sequence, fo.name
FROM folder fo
WHERE fo.parent_folder_id = 1
)
UNION ALL
(
SELECT 'file' AS type, fi.id, fi.sequence, NULL
FROM file fi
WHERE fi.parent_folder_id = 1
)
ORDER BY sequence;