2015-12-07 80 views
0

給定一組嵌套在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 

我怎樣可以得到如祖先:「閃光」,其中條件等級爲> = 50,< = 99 LIMIT 1排序由lft DESC。 所以其結果將是

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

可視化參考此鏈接 http://mikehillyer.com/media//categories.png

+0

在模型中,除了圖片之外什麼指示「便攜式電子設備」是「快閃」的祖先? – Anton

+0

這是左邊的列.. – Harts

+0

那麼如何解釋這些lft,rgt? – Anton

回答

1

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; 

SQL Fiddle

0

你沒有足夠的標識符的祖先之間的區分,只具有「50」的排名犯規區分記錄。

如果你做了一個

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

會給你「便攜式電子設備」,「電視」和「電子」,這些都是技術上的祖先。

如果您添加了另一個列字段,即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  | 

我會添加一個評論,但我沒有足夠的聲譽。希望這有點回答你的問題。