【问题标题】:Merge data from 2 tables in MySQL在 MySQL 中合并 2 个表中的数据
【发布时间】:2020-01-13 19:55:59
【问题描述】:

我在 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_idNULL,则表示该文件夹位于目录的根目录中。至于文档,它可以在另一个文件夹或根目录中(folder_id 为空)。我想要实现的是获得这样的选择数据:

例如,如果 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    |

它将选择所有具有该列的文件夹和文件

【问题讨论】:

    标签: mysql database select jointable


    【解决方案1】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      • 2014-03-30
      • 1970-01-01
      • 1970-01-01
      • 2022-11-08
      • 2015-08-22
      相关资源
      最近更新 更多