MySQL analog Oracle adjacency Model tree Processing

Source: Internet
Author: User
Tags joins

Database on the hierarchy of the processing model has a lot of, can according to their own needs to design models, of course, the simplest is the most easily designed model is called adjacency model. In this regard, other databases such as Oracle provide a ready-made analysis method for connect by, and MySQL is a bit weak in this regard. However, Oracle's similar analytics can be implemented with MySQL stored procedures


In this way, first create a simple tables.
CREATE TABLE Country (ID number (2) not NULL,  name varchar is NOT NULL), CREATE TABLE Country_relation (ID number (2), C1/>parentid number (2));




Insert some data
--Table Country.insert into country (id,name) values (0, ' Earth '); Insert to Country (id,name) VALUES (2, ' North America ') INSERT into country (id,name) VALUES (3, "South America"), insert into country (id,name) VALUES (4, ' Europe '); INSERT into Co Untry (Id,name) VALUES (5, ' Asia '), insert into country (Id,name) VALUES (6, ' Africa ') and insert into country (id,name) VALUES ( 7, ' Australia '); insert into country (id,name) VALUES (8, ' Canada '); Insert to Country (Id,name) VALUES (9, ' central America INSERT into country (id,name) VALUES ("Island Nations"), insert into country (id,name) values (one, ' one states '); SERT into country (id,name) VALUES ("Alabama"), insert into country (id,name) VALUES ("Alaska"), insert into country ( Id,name) VALUES ("Arizona"), insert into country (id,name) VALUES ("Arkansas"), insert into country (id,name) VALUES ( ' California ');--Table Country_relation.insert into country_relation (Id,parentid) values (0,null); INSERT INTO Country_relation (Id,parentid) VALues (2,0); insert into country_relation (Id,parentid) VALUES (3,0), insert into country_relation (Id,parentid) VALUES (4,0 Insert into country_relation (Id,parentid) VALUES (5,0), insert into country_relation (Id,parentid) values (6,0); insert Into Country_relation (Id,parentid) VALUES (7,0), insert into country_relation (Id,parentid) VALUES (8,2), insert INTO Coun Try_relation (Id,parentid) VALUES (9,2), insert into country_relation (Id,parentid) VALUES (10,2), insert into Country_ Relation (Id,parentid) values (11,2), insert into country_relation (Id,parentid) VALUES (12,11), insert into Country_ Relation (Id,parentid) values (13,11), insert into country_relation (Id,parentid) VALUES (14,11), insert into Country_ Relation (Id,parentid) values (15,11); insert into country_relation (Id,parentid) values (16,11);



In Oracle, these operations are relatively straightforward and are provided by the system.
For example, the following four scenarios:
1). View depth,
Select Max (level) ' level ' from country_relation a start with A.parentid are nullconnect by PRIOR a.id = A.parentidorder by level;     Level----------         4 time:  00:00:00.03




2). View leaf nodes
Select name from (select B.name, connect_by_isleaf "IsLeaf" from Country_relation a inner joins country B on (a.id = b.id) s Tart with A.parentid are NULL connect by prior a.id = A.parentid) T where T. " IsLeaf "= 1; NAME--------------------------------------------------canadacentral Americaisland Nationsalabamaalaskaarizonaarkansascaliforniasouth Americaeuropeasiaafricaaustralia has selected 13 rows. Time used:  00:00:00.01



3) View the root node
Select Connect_by_root b.namefrom country_relation a INNER join country B on (a.id = b.id) Start with A.parentid is NULL C Onnect by a.id = A.parentid CONNECT_BY_ROOTB. NAME--------------------------------------------------Earth Time:  00:00:00.01



4). View Path
Select Sys_connect_by_path (B.name, '/') "path" from Country_relation a inner joins country B on (a.id = b.id) Start with A.P Arentid is a NULL connect by prior a.id = A.parentid ORDER by Level,a.id;path---------------------------------------------- ----/earth/earth/north America/earth/south america/earth/europe/earth/asia/earth/africa/earth/australia/earth/ North America/canada/earth/north america/central America/earth/north america/island Nations/earth/north America/ States/earth/north america/united States/alabama/earth/north america/united States/alaska/earth/north America /united States/arizona/earth/north america/united States/arkansas/earth/north america/united States/ California has selected 16 rows. Time used:  00:00:00.01




Let's look at how the above four scenarios are implemented in MySQL:
The first three are relatively simple and can be easily written out in SQL.
1) View Depth
Mysql> SELECT COUNT (DISTINCT ifnull (parentid,-1)) as level from country_relation;+-------+| Level |+-------+|     4 |+-------+1 row in Set (0.00 sec)



2) View the root node
Mysql> Select B. ' Name ' as Root_node from    (-a    select  ID from country_relation WHERE parentid is NU LL    -C) as a, country as b WHERE a.id = b.id;+-----------+| Root_node |+-----------+| Earth     |+-----------+1 row in Set (0.00 sec)



3). View leaf nodes
Mysql> Select B. ' Name ' as Leaf_node from    (-a    select  ID from country_relation WHERE ID not in (SEL ECT ifnull (parentid,-1) from country_relation)    as a, country as b WHERE a.id = b.id;+-----------------+| Leaf_node       |+-----------------+| South America   | | Europe          | | Asia            | | Africa          | | Australia       | | Canada          | | Central America | | Island Nations  | | Alabama         | | Alaska          | | Arizona         | | Arkansas        | | California      |+-----------------+13 rows in Set (0.00 sec)





4) View Path
This piece does not have a simple SQL implementation, but you can use the MySQL stored procedure to achieve the same functionality.
The stored procedure code is as follows:


DELIMITER $ $USE ' t_girl ' $ $DROP PROCEDURE IF EXISTS ' sp_show_list ' $ $CREATE definer= ' root ' @ ' localhost ' PROCEDURE ' sp_show      _list ' () BEGIN--Created by Ytt 2014/11/04.      --is equal to Oracle's connect by syntax.      -Body.      DROP TABLE IF EXISTS tmp_country_list;      CREATE temporary TABLE tmp_country_list (node_level INT UNSIGNED not NULL, Node_path VARCHAR (+) not NULL);      --Get the root node.      INSERT into Tmp_country_list SELECT 1, CONCAT ('/', id) from country_relation WHERE ParentID is NULL;      --Loop within all parent node.        Cursor1:begin DECLARE done1 INT DEFAULT 0;        DECLARE i1 INT DEFAULT 1;        DECLARE V_parentid INT DEFAULT-1;        DECLARE V_node_path VARCHAR (+) DEFAULT '; DECLARE CR1 CURSOR for SELECT parentid from Country_relation WHERE ParentID was not NULL GROUP by ParentID ORDER by parent        ID ASC;                DECLARE CONTINUE HANDLER for not FOUND SET done1 = 1;                OPEN CR1;         Loop1:loop FETCH CR1 into V_parentid;          IF done1 = 1 then LEAVE loop1;          END IF;                    SET I1 = i1 + 1;            Label_path:begin DECLARE done2 INT DEFAULT 0;            DECLARE CONTINUE HANDLER for not FOUND SET done2 = 1;            --Get the upper path. SELECT Node_path from tmp_country_list WHERE node_level = i1-1 and LOCATE (V_parentid,node_path) > 0 into V_node_path            ;            --Escape The outer not found exception.            IF done2 = 1 then SET done2 = 0;            END IF; INSERT into Tmp_country_list SELECT i1,concat (ifnull (V_node_path, "), '/', id) from country_relation WHERE Parent          id = v_parentid;        END;                END LOOP;              CLOSE CR1;      END;      --Update node ' s ID to its real name.        Update_name_label:begin DECLARE cnt INT DEFAULT 0;        DECLARE i2 INT DEFAULT 0;        SELECT MAX (node_level) from tmp_country_list to CNT; WhileI2 < CNT do UPDATE tmp_country_list as a, country as b SET a.node_path = REPLACE (A.node_path,          CONCAT ('/', b.id), CONCAT ('/', b.name)) WHERE LOCATE (CONCAT ('/', b.id), A.node_path) > 0;        SET i2 = i2 + 1;      END while;          END;    SELECT Node_path from Tmp_country_list; end$ $DELIMITER;




Call Result:
Mysql> call Sp_show_list (); +-----------------------------------------------+| Node_path |+-----------------------------------------------+| /earth | | /earth/north America | | /earth/south America | | /earth/europe | | /earth/asia | | /earth/africa | | /earth/australia | | /earth/north America/canada | | /earth/north America/central America | | /earth/north America/island Nations | | /earth/north america/united States | | /earth/north america/united States/alabama | | /earth/north america/united States/alaska | | /earth/north america/united States/arizona | | /earth/north america/united States/arkansas | | /earth/north america/united States/california |+-----------------------------------------------+16 rows in Set (0.04 sec) Query OK, 0 rows affected (0.08 sec) 


MySQL analog Oracle adjacency Model tree Processing

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.