sql >> Database teknologi >  >> RDS >> Mysql

MySQL Nested Sets - Hvordan finder man forælder til node?

Se på dette spørgsmål . Den ligner din. Jeg har postet en forespørgsel, du muligvis har brug for.

SELECT title, (SELECT TOP 1 title FROM tree t2 WHERE t2.lft < t1.lft AND t2.rgt > t1.rgt ORDER BY t2.rgt-t1.rgt ASC) AS parent FROM tree t1 ORDER BY rgt-lft DESC

Jeg håber, at der er det, du har brug for.

For følgende tabel:

+-------------+----------------------+-----+-----+ | category_id | name | lft | rgt | +-------------+----------------------+-----+-----+ | 1 | ELECTRONICS | 1 | 20 | | 2 | TELEVISIONS | 2 | 9 | | 3 | TUBE | 3 | 4 | | 4 | LCD | 5 | 6 | | 5 | PLASMA | 7 | 8 | | 6 | PORTABLE ELECTRONICS | 10 | 19 | | 7 | MP3 PLAYERS | 11 | 14 | | 8 | FLASH | 12 | 13 | | 9 | CD PLAYERS | 15 | 16 | | 10 | 2 WAY RADIOS | 17 | 18 |

det producerer output:

title                | parent
----------------------------------------------
ELECTRONICS          | NULL
PORTABLE ELECTRONICS | ELECTRONICS
TELEVISIONS          | ELECTRONICS
MP3 PLAYERS          | PORTABLE ELECTRONICS
FLASH                | MP3 PLAYERS
CD PLAYERS           | PORTABLE ELECTRONICS
2 WAY RADIOS         | PORTABLE ELECTRONICS
TUBE                 | TELEVISIONS
LCD                  | TELEVISIONS
PLASMA               | TELEVISIONS
 


  1. array_agg for arraytyper

  2. Oracle DROP TABEL HVIS FINDER Alternativer

  3. PHP PDO MySQL-forespørgsel LIKE -> flere søgeord

  4. Vil du slette alle poster undtagen den seneste?