Question

It's been a long time since I last did something with database so my knowledge has beenyet rusted. I have 2 SQL tables:

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

I need to query all the attr corresponding to the entries in table dependency. Following is my attempt:

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;

It works but very slow. I'm sure there's a better way to do it with join query but cannot come up with it yet. Can someone please help?

Thanks,

Was it helpful?

Solution

You could join the dependency table to the data table twice to get the information you need:

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

OTHER TIPS

try this:

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top