需要更高效的连接查询

时间:2013-12-04 18:33:44

标签: mysql sql join jointable

自从我上次对数据库做了一些事情已经有很长一段时间了,所以我的知识已经生效了。我有2个SQL表:

data(id, attr);
dependency(child, parent);
 #**child** and **parent** are the id from table **data**

我需要查询与表依赖关系中的条目相对应的所有 attr 。以下是我的尝试:

SELECT 
(SELECT data.attr FROM data WHERE data.id = child) AS child_attr,
(SELECT data.attr FROM data WHERE data.id = parent) AS parent_attr 
from dependency;

虽然有效但很慢。我确信有一个更好的方法来使用连接查询,但还不能提出它。  有人可以帮忙吗?

谢谢,

2 个答案:

答案 0 :(得分:1)

您可以将dependency表加入data表两次以获取所需信息:

SELECT d1.attr AS ChildAttr, d2.attr AS ParentAttr
FROM dependency AS dep
INNER JOIN data AS d1 ON dep.child = d1.id
INNER JOIN data AS d2 ON dep.parent = d2.id

答案 1 :(得分:1)

试试这个:

SELECT t2.attr, t3.attr
FROM dependency as t1
    INNER JOIN data as t2 on t1.child = t2.id
    INNER JOIN data as t3 on t1.parent = t3.id