2015-12-30 66 views
-1

什麼查詢獲取記錄結果在同一個表中?MySql查詢從樹表中獲取記錄

我的表是這樣的:

id uid name status parent 
1 1t01 AAA Teacher root 
2 2s01 CCC Student 1t01 
3 3t02 BBB Teacher root 
4 4s02 DDD Student 3t02 
5 5s03 EEE Student 1t01 

在那裏我有名稱:DDD,我贏了顯示老師的名字:BBB

什麼查詢得到老師的名字:BBB

解決

答案來自Martin

SqlFiddle

+0

請給出撕裂器表的結構?以及該表中爲維護關係而製作的任何主鍵? –

回答

0

你可以加入本身的表,就像這樣:

SELECT p.name teacher 
FROM table_name t 
INNER JOIN table_name p 
    ON p.uid = t.parent 
WHERE t.name = 'BBB'; 
0
select * from table Name where name="BBB" 
0

聯袂同臺會這麼做:

SELECT t2 .name as teacherName 
FROM t1 
JOIN t1 AS t2 ON t1.parent = t2.uid 
WHERE t1.name = 'BBB'; 
1

您的查詢應該是這樣的:

SELECT t2.name 
FROM yourtable t1, yourtable t2 
WHERE t1.parent = t2.uid 
AND t1.name = 'DDD'; 

替換yourtable與您的實際表名稱。