合并 MySQL 中 2 个表的数据

Merge data from 2 tables in MySQL

我在 MySQL 中有 2 个这样的表文件夹结构:

文件夹 Table:

|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    |

文档 Table:

|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 检索文件夹和文件,这一列是为了标记一个文件夹是否在另一个文件夹内所以另一个文件夹将是 parent。如果 folder_parent_idNULL,则表示该文件夹位于目录的根目录中。至于文档,它可以在另一个文件夹中或在根目录中(folder_id 为空)。我想要实现的是获得这样的 select 数据:

例如 folder_parent_id 为 NULL AND 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所有文件夹和文件都有这样的列

如果我明白你想要什么,我想你需要这样的东西:

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