简体   繁体   中英

mysql - relating multiple rows

I have a table,

SLNO|   ID  |CHILD ID
  1 |   1   | 200
  2 |   1   | 250
  3 |   250 | 350
  4 |   7   | 8

Can we have a query to, extract all the values of 1 , ie 1, 200, 250, 350 in a single row ? SLNO being unique.

Firstly, are you sure you need to do that, to collapse multiple rows into a single row?

The most convenient shortcut would be to use a GROUP BY operation and a GROUP_CONCAT function.

MySQL doesn't have any native (built in) hierarchical query features.

You could emulate that, to a finite number of levels, with a pattern like this:

  SELECT GROUP_CONCAT(DISTINCT t.`CHILD_ID` ORDER BY t.`CHILD ID`) AS child_id_list 
    FROM ( 
           SELECT a1.`CHILD ID`
             FROM mytable a1
            WHERE a1.`ID` = 1

            UNION ALL 

           SELECT b2.`CHILD ID`
             FROM mytable b1
             JOIN mytable b2 ON b2.`ID` = b1.`CHILD ID`
            WHERE b1.`ID = 1

            UNION ALL

           SELECT c3.`CHILD ID`
             FROM mytable c1
             JOIN mytable c2 ON c2.`ID` = c1.`CHILD ID`
             JOIN mytable c3 ON c3.`ID` = c2.`CHILD ID` 
            WHERE c1.`ID` = 1

         ) t

This pattern can be extended to a finite number of levels.

            UNION ALL

           SELECT d4.`CHILD ID`
             FROM mytable d1
             JOIN mytable d2 ON d2.`ID` = d1.`CHILD ID`
             JOIN mytable d3 ON d3.`ID` = d2.`CHILD ID` 
             JOIN mytable d4 ON d4.`ID` = d4.`CHILD ID` 
            WHERE c1.`ID` = 1

etc.

The GROUP_CONCAT function returns a single column. The length of the returned string is limited to group_concat_max_len variable (and also by max_allowed_packet ). If the length of the string exceeds group_concat_max_len , the string value will be trimmed silently (without error or warning) to the maximum allowed length (in bytes) when it is returned.

 SELECT @@session.group_concat_max_len

To get a true recursion, for any number of levels, that can't be done in a single MySQL query using native builtin in functions. You could use a MySQL stored procedure to implement the required looping.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM