Skip to content

Instantly share code, notes, and snippets.

@LiYiBin
Last active September 12, 2017 06:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LiYiBin/3ee40d39098ad39a9cd9192b49f5aa3c to your computer and use it in GitHub Desktop.
Save LiYiBin/3ee40d39098ad39a9cd9192b49f5aa3c to your computer and use it in GitHub Desktop.
yb_cte_example.sql
#
CREATE DATABASE IF NOT EXISTS `test_cte`;
USE `test_cte` ;
#
CREATE TABLE IF NOT EXISTS `test_cte`.`trees` (
`id` INT NOT NULL ,
`parent_id` INT NULL ,
PRIMARY KEY (`id`) )
ENGINE = InnoDB;
#
INSERT INTO `test_cte` VALUES (1,3), (2,5), (3,NULL), (4,10), (5,NULL), (6,1), (7,5), (8,10), (9,10), (10,3);
5
├── 2
└── 7
3
├── 10
│ ├── 4
│ ├── 9
│ └── 8
└── 1
└── 6
#
with recursive ancestors as (
select *
from trees
where id = 4
union
select trees.*
from trees, ancestors AS a
where
trees.id = a.parent_id
)
select * from ancestors;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment