sql >> データベース >  >> RDS >> Mysql

MySQLClosureTable階層型データベース-正しい順序で情報を引き出す方法

    SELECT d.`iD`, d.`subsectionOf`,
           CONCAT(REPEAT('-', p.`len`), d.`name`) as hier,
           p.`len`, p.`ancestor`, p.`descendant`,
           GROUP_CONCAT(crumbs.`ancestor`) AS breadcrumbs
    FROM `TreeData` AS d
    JOIN `TreePaths` AS p ON d.`iD` = p.`descendant`
    JOIN `TreePaths` AS crumbs ON crumbs.`descendant` = p.`descendant`
    WHERE p.`ancestor` = 1
    GROUP BY d.`iD`
    ORDER BY breadcrumbs;
    
    +----+--------------+---------------------+-----+----------+------------+-------------+
    | iD | subsectionOf | hier                | len | ancestor | descendant | breadcrumbs |
    +----+--------------+---------------------+-----+----------+------------+-------------+
    |  1 |         NULL | Root A              |   0 |        1 |          1 | 1           | 
    |  2 |            1 | -Item 1             |   1 |        1 |          2 | 1,2         | 
    |  5 |            2 | --Item 1 Sub Item 2 |   2 |        1 |          5 | 1,2,5       | 
    |  6 |            2 | --Item 1 Sub Item 1 |   2 |        1 |          6 | 1,2,6       | 
    |  3 |            1 | -Item 2             |   1 |        1 |          3 | 1,3         | 
    |  4 |            1 | -Item 3             |   1 |        1 |          4 | 1,4         | 
    |  8 |            4 | --Item 3 Sub Item 1 |   2 |        1 |          8 | 1,4,8       | 
    |  9 |            4 | --Item 3 Sub Item 2 |   2 |        1 |          9 | 1,4,9       | 
    |  7 |            1 | -Item 4             |   1 |        1 |          7 | 1,7         | 
    +----+--------------+---------------------+-----+----------+------------+-------------+
    



    1. とにかくメジャーバージョンとは何ですか?

    2. MySQL SELECT x FROM a WHERE NOT IN(SELECT x FROM b)-予期しない結果

    3. 1つのMySQLクエリで複数の行を更新する

    4. 動的LIMITを使用してSQLクエリを作成する方法