0

如果我的数据库看起来像这样:-

| CATAGORY_ID | CATAGORY_NAME | PARENT_ID |
-------------------------------------------
|           1 |             x |         0 |
|           2 |             y |         1 |
|           3 |             z |         2 |

我用它来获得一个层次结构,但我希望 ds 运行直到它的 get parent_id = 0

SELECT catagory_name
FROM catagory_master
WHERE catagory_id = ( 
SELECT parent_id
FROM catagory_master
WHERE catagory_id =4 ) 

如果我想要 xyz 用于 catagory_id=3 和 xy 用于 catagory_id=2 和 x 用于 catagory_id=1 请帮助我必须在 php 脚本中运行它

4

3 回答 3

1

试试这个查询

select 
catagory_id,
catagory_name,
@pv:=parent_id as 'parent_id'
from (select * from table1 order by catagory_id desc)a
join
(select @pv:=3)tmp
where catagory_id=@pv

SQL 小提琴

| CATAGORY_ID | CATAGORY_NAME | PARENT_ID |
-------------------------------------------
|           3 |             z |         2 |
|           2 |             y |         1 |
|           1 |             x |         0 |

注意:parent_id如果总是小于该记录的,则此查询将起作用category_id。如果您将按 desc 字段删除订单,您将仅获得 1 条记录。如果您想要一个适当的具体解决方案,而不是需要一个存储过程..

于 2013-05-24T06:59:47.823 回答
0

如果我得到你想要的,你需要为此使用 IN!

SELECT catagory_name
FROM catagory_master
WHERE catagory_id IN ( 
    SELECT parent_id
    FROM catagory_master
    WHERE catagory_id = 4 ) 
于 2013-05-24T06:44:21.410 回答
0

If your database supports RECURSIVE queries, you can do something like this:

WITH RECURSIVE category_tree(id, name, path, level) AS (
        SELECT catagory_id, catagory_name, ARRAY[id], 0
    FROM catagory_master
    WHERE parent_id = 0
    UNION ALL
    SELECT catagory_master.catagory_id, catagory_master.catagory_name, path || catagory_master.catagory_id, level + 1
    FROM category_tree
    JOIN catagory_master ON catagory_master.parent_id = category_tree.catagory_id
    WHERE NOT catagory_master.catagory_id = ANY(path)
    )
    SELECT * FROM category_tree where 0 = ANY(path) ORDER BY path ;

And you should have something like this, that can be used to buid a tree:

enter image description here

于 2013-05-24T06:57:05.760 回答