SQL的问题,单个表多连接

来源:百度知道 编辑:UC知道 时间:2024/06/09 09:14:39
请选看图,地址: http://www.microsoft.com/china/community/Columns/Lihonggen/image/1-1.jpg

我想查询 ID = 6,
显示出来后是 ID= 6,Context=广州,ParentID=5
我想要的效果是 ID= 6,Context=广州,ParentID=广东省
也就是说 ParentID=5 显示的是 ID=5 中的 广东省。

有没有办法 用一句 SQL 语句就能查询到呢,
我现在用的是要2句SQL 才可以查到,如下
select ParentID,ConText from 表 where ID =6
然后
select ConText from 表 where ID = 刚才查到的ParentID

2句的话比较麻烦,有没有办法一句就查到?
显示的结果是 6,广州,广东省。

把这一张表看成两张表,用字段a.ID=b.ParentID 做表连接查询
select a.id,a.context,b.context from A a,B b
where a.id='6' and a.id=b.ParentID

我给你写个例子吧
select context from 表 where id in (select parentid from 表 where parentid=6)
这个可以把广东省显示出来,但是不能显示广州

select A.ID,A.Context,B.Context from 表 A
left join 表 B
on A.ID = B.ParentID
where A.ID = 6

select a.ParentID,a.ConText,b.ConText from 表a,表b where a.ID = 6 and a.ID = b.ID

假设你图里的表是A,广东省的那张表是B
select a.id,a.context,b.parentID from A a,B b
where a.id='6' and a.id=b.id