MySQL Stored Procedure Design Problem. Recusion or Hierarchy?

青春壹個敷衍的年華 提交于 2019-12-11 08:04:43

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/6602416/mysql-stored-procedure-design-problem-recusion-or-hierarchy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!