我试图从不同的表中获取文件夹和文件名,并使用EACH查询语句的结果,按其update_date
的降序排序,然后使用UNION
进行连接。
如果我分别运行这两个查询,它确实起作用,并且结果将根据日期的降序从数据库中检索。但是当我将UNION
与它们一起使用时,它并没有给出正确的答案。
获取它的正确方法是什么?
(
SELECT create_date, folder_name AS actual_name, folder_id, folder_displayed_name AS displayed_name, update_date, delete_flag, NULL AS img_url, NULL AS protect_flag, NULL AS file_type, list_order
FROM aaaaa_estate.docs_folder
WHERE delete_flag =0
AND inside_of_folder = ''
ORDER BY update_date DESC
)
UNION (
SELECT create_date, file_name AS actual_name, id, displayed_name, update_date, delete_flag, img_url, protect_flag, file_type, list_order
FROM aaaaa_estate.docs_contract
WHERE delete_flag =0
AND inside_of = ''
ORDER BY update_date DESC
)
如果我在最后使用Order By子句。它将基于我从未想要的update_date
ORDER BY DESC
排序所有数据。
我想向用户显示文档列表,例如Google展示在Google云端硬盘中,始终显示“始终文件夹”,然后显示文件。他们每个人都按update_date DESC
答案 0 :(得分:1)
您可以尝试以下操作,其中ORDER BY
子句取决于两列:
SELECT * FROM
(
SELECT 1 qry_nr, create_date, folder_name AS actual_name, folder_id, folder_displayed_name AS displayed_name, update_date, delete_flag, NULL AS img_url, NULL AS protect_flag, NULL AS file_type, list_order
FROM aaaaa_estate.docs_folder
WHERE delete_flag =0
AND inside_of_folder = ''
UNION
SELECT 2 qry_nr, create_date, file_name AS actual_name, id, displayed_name, update_date, delete_flag, img_url, protect_flag, file_type, list_order
FROM aaaaa_estate.docs_contract
WHERE delete_flag =0
AND inside_of = ''
-- ORDER BY update_date DESC
) q
ORDER BY q.actual_name, q.qry_nr;
答案 1 :(得分:0)
在子查询中按使用顺序
select t.* from
(
SELECT 1 as type, create_date, folder_name AS actual_name, folder_id, folder_displayed_name AS displayed_name, update_date, delete_flag, NULL AS img_url, NULL AS protect_flag, NULL AS file_type, list_order
FROM aaaaa_estate.docs_folder
WHERE delete_flag =0
AND inside_of_folder = ''
UNION
SELECT 2 ,create_date, file_name AS actual_name, id, displayed_name, update_date, delete_flag, img_url, protect_flag, file_type, list_order
FROM aaaaa_estate.docs_contract
WHERE delete_flag =0
AND inside_of = ''
) t order by type asc, update_date desc
正如您提到的,始终将文件夹放在第一位,然后将文件放在第二位,因此将其分为两种类型以保持正确的顺序