[英]Get nested set ancestor where condition
Given a nested set in mysql like this 在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
How can I get an ancestor for eg: "Flash" where condition rank is >=50 AND <= 99 LIMIT 1 sorted by lft DESC. 我如何获得祖先,例如:“ Flash”,其中条件等级> = 50 AND <= 99 LIMIT 1(按lft DESC排序)。 so the result will be
所以结果将是
+-------------+----------------------+-----+-----+------+
| category_id | name | lft | rgt | rank |
+-------------+----------------------+-----+-----+------+
| 6 | PORTABLE ELECTRONICS | 10 | 19 | 50
for visualization refer to this link http://mikehillyer.com/media//categories.png 要进行可视化,请参阅此链接http://mikehillyer.com/media//categories.png
sql fiddle is not working for me right now, but you should be able to do something like this. sql小提琴现在对我不起作用,但是您应该可以执行以下操作。
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;
You dont have enough identifiers to differentiate between ancestors, having just "50" for a ranking doesnt differentiate the records. 您没有足够的标识符来区分祖先,排名只有“ 50”并不能区分记录。
If you did a 如果你做了
SELECT * FROM [SET] WHERE RANK >= 50 AND RANK <= 99
Would give you "Portable Electronics", "Televisions", and "Electronics", which are all technically ancestors. 会给您“便携式电子产品”,“电视”和“电子产品”,它们都是技术上的祖先。
If you added another column field, ie parent_id then it would make it much easier to build structure from the data. 如果添加了另一个列字段,即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
Or implementing a relationship table to hold those data sets 或实现关系表来保存这些数据集
+------+--------+
| Item | Parent |
+------+--------+
| 2 | 1 |
| 3 | 2 |
I would have added as a comment, but i don't have enough reputation. 我会添加为评论,但是我没有足够的声誉。 hope this answers your question somewhat.
希望这能回答您的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.