列视图
+-----------------------+
| name |
+-----------------------+
| ELECTRONICS |
| TELEVISIONS |
| TUBE |
| LCD |
| PLASMA |
| GAME CONSOLES |
| PORTABLE ELECTRONICS |
| MP3 PLAYERS |
| FLASH |
| CD PLAYERS |
| 2 WAY RADIOS |
| FRS |
+-----------------------+
table core.category
Id ParentId Name
1 null ELECTRONICS
2 1 TELEVISIONS
3 2 TUBE
4 2 LCD
5 2 PLASMA
6 1 GAME CONSOLES
7 1 PORTABLE ELECTRONICS
8 7 MP3 PLAYERS
9 8 FLASH
10 7 CD PLAYERS
11 1 2 WAY RADIOS
12 11 FRS
如果我选择1,
结果是(显示儿童和孙子)期望有超过1个祖父母(电子)
+-----+
| id |
+-----+
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| 6 |
| 7 |
| 8 |
| 9 |
| 10 |
| 11 |
| 12 |
+-----+
如果我选择2
结果必须是
+-----+
| id |
+-----+
| 2 |
| 3 |
| 4 |
| 5 |
+-----+
我选择了这个类别和他的孩子(需要更多输出孙子)
module.exports.categorySearch = function(searchCategory, cb) {
var query = 'SELECT category_id \
FROM core.category AS c \
WHERE category_id = $1::integer
UNION
SELECT category_id \
FROM core.category AS c \
WHERE category_ParentId = $1::integer
;';
var map = function(err, result) {
if(err) {
return cb(err, null);
}
var list = [];
result.rows.forEach(function(row, i) {
list.push(new Category(row));
});
cb(null, list);
};
repository.queryDb(query, [searchCategory], map);
};
结果是
+-----+
| id |
+-----+
| 1 |
| 2 |
| 6 |
| 7 |
| 11 |
+-----+
我应该在我的选择陈述中添加什么
答案 0 :(得分:0)
WITH RECURSIVE categorytree AS (
SELECT c.category_id, 0 as depth
FROM core.category AS c
WHERE c.category_id = $1::integer
UNION ALL
SELECT c.category_id, t.depth + 1 as depth
FROM core.category AS c
INNER JOIN categorytree t
ON t.category_id = c.category_ParentId
)
SELECT category_id FROM categorytree
显示所选的儿童和孙子女等...
+-----+
| id |
+-----+
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| 6 |
| 7 |
| 8 |
| 9 |
| 10 |
| 11 |
| 12 |
+-----+