获取嵌套set ancestor where condition

时间:2015-12-07 21:07:57

标签: mysql sql sql-order-by nested-sets

在mysql中给出一个像这样的嵌套集

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

我怎样才能得到一个祖先,例如:" Flash"其中条件等级是> = 50并且< = 99 LIMIT 1按lft DESC排序。 所以结果将是

+-------------+----------------------+-----+-----+------+
| category_id | name                 | lft | rgt | rank |
+-------------+----------------------+-----+-----+------+
|           6 | PORTABLE ELECTRONICS |  10 |  19 |  50

用于可视化,请参阅此链接 http://mikehillyer.com/media//categories.png

2 个答案:

答案 0 :(得分:1)

sql fiddle现在不适合我,但是你应该可以做这样的事情。

SELECT  
    c2.* 
FROM
    Categories as c1
    INNER JOIN Categories as c2 ON 
            c1.`lft` >= c2.lft AND c1.`lft` <= c2.`rgt` 
            AND c2.`RANK` >=50 AND c2.`RANK` <= 99 
WHERE 
    c1.`category_id` = 8
ORDER BY 
    c2.`lft` DESC
LIMIT 1;

SQL Fiddle

答案 1 :(得分:0)

你没有足够的标识符来区分祖先,只有&#34; 50&#34;排名不能区分记录。

如果你做了

SELECT * FROM [SET] WHERE RANK >= 50 AND RANK <= 99

会给你&#34;便携式电子产品&#34;,&#34;电视&#34;和&#34;电子产品&#34;,它们都是技术上的祖先。

如果添加了另一个列字段,即parent_id,则可以更轻松地从数据构建结构。

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

或实现关系表来保存这些数据集

+------+--------+
| Item | Parent |
+------+--------+
|  2   |  1     |
|  3   |  2     |

我会添加评论,但我没有足够的声誉。希望这会在某种程度上回答你的问题。