1

你好朋友我在连接查询中有些困惑,所以我写了子查询。我的数据库设计是这样的:table name = dbtest

------------------------
| id | name | relation |
------------------------
| 1  | abc  |    2     |
| 2  | bbc  |    0     |
| 3  | kbc  |    2     |
| 4  | xyz  |    3     |
------------------------

我想要根据谁与谁相关的输出。

假设如果我输入id = 4它应该返回xyz => kbc

通过子查询到目前为止我已经实现的kbc只是
我的子查询是:select name from dbtest where id = (select relation from dbtest where id = '3');

任何伙伴可以帮助我使用连接查询获得所需的输出吗?

4

5 回答 5

1
select name
from dbtest
where id = (
  select relation
  from dbtest
  where id = '3'
);

(yours) 等价于 (s 是内部选择,r 是外部选择)

select r.name
from dbtest s
join dbtest r
  on r.id = s.relation
where s.id = '3'
于 2013-02-19T07:33:04.363 回答
1

我设法得到了xyz => kbc与这个查询的关系:

SELECT a.name, b.name from dbtest a, dbtest b where a.id = 4 and a.relation = b.id

编辑:这是使用 JOIN 的相同查询

SELECT a.name, b.name FROM dbtest a JOIN dbtest b ON a.relation = b.id WHERE a.id = 4
于 2013-02-19T07:39:01.303 回答
0
select d.name,d.id,db.relation from dbtest d, dbtest db where d.id = db.relation;

这是自我加入...希望对您有所帮助

于 2013-02-19T07:32:57.090 回答
0

试试这个:

select a.id,a.name,b.name,b.relation 
from dbtest a,dbtest b where a.id=b.relation
于 2013-02-19T07:38:35.217 回答
-1
select name from dbtest where relation ='3';
                  OR
//if id is dynamic value
select name from dbtest where relation ='$id';
于 2013-02-19T07:45:59.067 回答