Php MySql查询从树表中获取记录
如果结果在同一个表中,要获取记录的查询是什么 我有这样的桌子:Php MySql查询从树表中获取记录,php,mysql,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 SELECT t2.name FROM yourtable t1, yourta
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
SELECT t2.name
FROM yourtable t1, yourtable t2
WHERE t1.parent = t2.uid
AND t1.name = 'DDD';
我的名字是:DDD,我的名字是:BBB
获取教师姓名的查询:BBB
解决
马丁的回答
您可以在表本身上加入,如下所示:
SELECT p.name teacher
FROM table_name t
INNER JOIN table_name p
ON p.uid = t.parent
WHERE t.name = 'BBB';
连接同一个表将执行以下操作:
SELECT t2 .name as teacherName
FROM t1
JOIN t1 AS t2 ON t1.parent = t2.uid
WHERE t1.name = 'BBB';
您的查询应如下所示:
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
SELECT t2.name
FROM yourtable t1, yourtable t2
WHERE t1.parent = t2.uid
AND t1.name = 'DDD';
将
yourtable
替换为实际的表名。请给出tearcher表的结构?还有表中用来维护关系的主键吗?