我在 MySQL 中有 2 个这样的表文件夹结构:
文件夹表:
|folder_id | folder_parent_id | folder_name | is_active|
+----------+------------------+-------------+----------+
| 1 | NULL | Desktop | 1 |
| 2 | NULL | Downloads | 1 |
| 3 | 2 | Movies | 1 |
| 4 | 2 | Musics | 0 |
| 5 | 1 | Trash | 1 |
| 6 | NULL | Systems | 1 |
| 7 | NULL | Locals | 0 |
文档表:
|document_id | folder_id | document_name | document_status |
+------------+------------+---------------+-------------------+
| 1 | NULL | Invoice | approved |
| 2 | 3 | Subtitle | approved |
| 3 | 4 | Lyrics | not_approved |
| 5 | 6 | ReadME | approved |
| 6 | 2 | Script | approved |
所以基本上这两个表是用于我的文件管理器系统的,我需要根据folder_parent_id
检索文件夹和文档,此列用于标记一个文件夹是否位于另一个文件夹内,因此另一个文件夹文件夹将是父文件夹。如果 folder_parent_id
为 NULL
则表示该文件夹位于目录的根目录中。至于文档,它可以位于另一个文件夹内或根目录中(folder_id
为空)。我想要实现的是获取这样的选择数据:
例如,如果folder_parent_id为NULL且is_active = 1:
|folder_id | folder_name | document_id |document_status|document_name|
|----------+-------------+--------------+---------------+-------------+
| 1 | Desktop | NULL | NULL | NULL |
| 2 | Downloads | NULL | NULL | NULL |
| 6 | Systems | NULL | NULL | NULL |
| NULL | NULL | 1 | approved | Invoice |
例如,如果 folder_parent_id
为 2 AND is_active
= 1:
|folder_id | folder_name | document_id |document_status|document_name|
|----------+-------------+--------------+---------------+-------------+
| 3 | Movies | NULL | NULL | NULL |
| 4 | Musics | NULL | NULL | NULL |
| NULL | NULL | 6 | approved | Script |
它将选择具有类似列的所有文件夹和文件
最佳答案
如果我明白你想要什么,我认为你需要这样的东西:
SELECT folder_id, folder_name,
NULL AS document_id, NULL as document_status, NULL as document_name
FROM folders
WHERE folder_parent_id = your_number AND is_active = 1
UNION
SELECT NULL as folder_id, NULL as folder_name,
document_id, document_status, document_name
FROM documents
WHERE folder_id = your_number AND is_active = 1
关于mysql - 合并 MySQL 中 2 个表的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59716062/