MySql Query从树表中获取记录

时间:2015-12-30 06:54:29

标签: php 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

解决

马丁的回答

SqlFiddle

4 个答案:

答案 0 :(得分:1)

您的查询应该是这样的:

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

yourtable替换为您的实际表名。

答案 1 :(得分:0)

你可以自己加入表格,如下:

SELECT p.name teacher
FROM table_name t
INNER JOIN table_name p
  ON p.uid = t.parent
WHERE t.name = 'BBB';

答案 2 :(得分:0)

select * from table Name where name="BBB"  

答案 3 :(得分:0)

加入同一个表格将会这样做:

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