开发者

MySQL Stored Procedure Design Problem. Recusion or Hierarchy?

开发者 https://www.devze.com 2023-03-18 07:15 出处:网络
Suppose we have a table named SMALLER, with column num_1 and num_2, both integer type, and some data in it.

Suppose we have a table named SMALLER, with column num_1 and num_2, both integer type, and some data in it.

It looks like this:

`num_1`  `num_2` 
    1        2
    2        3
    2        8
    3        4
    4        5
        .
        .
        .  Much much much more
        .  

What Im trying t开发者_如何学编程o do is expand this table, and then collect all "Smaller" relations. Such that, the result table should looks like this:

`num_1`  `num_2` 
    1        2
    1        3
    1        4
    1        5
    1        8
    2        3
    2        4
    2        5
    2        8
    3        4
    3        5
    4        5

I appreciate all helps !

Futhermore, what if instead of "smaller" relations, this table just have a "connected" relation, for instance, '1' connected to '2', '2' connected to '3', '2' connected to '4', such that we say 1-2, 1-3, 1-4, 2-3, 2-4.


A good place to start would be:

SELECT 
    A.num_1, B.num_2 
FROM 
    Smaller AS A JOIN Smaller AS B ON (A.num_1 < B.num_2) 
ORDER BY A.num_1, B.num_2;

Inside your stored procedure, put this into a cursor, iterate over the cursor and for each row do a INSERT IGNORE. Ie:

DECLARE num1,num2 INT;
DECLARE done DEFAULT 0;
DECLARE mycursor CURSOR FOR SELECT # use the select above, im lazy here
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

OPEN mycursor;

my_loop: LOOP
    FETCH mycursor INTO num1, num2;
    IF done THEN
       LEAVE my_loop;
    END IF;
    INSERT IGNORE INTO Smaller VALUES (num1,num2);
END LOOP;

To answer your updated question, whiles not entirely sure if you mean connected as by means of relations between unique rows (you would need two columns to store this relation, so it would be quite similar). Or if you mean you have one table containing all numbers, and another two column table containing relations between the rows of the first table.

Or, finally, if you want a table just containing strings with "1-2", "1-3" etc. If thats the case, I would keep it as two individual columns and just output them as strings using CONCAT when you poll the table :)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号