使用具有关系的表在一个表中获取相关行

时间:2013-05-18 11:33:52

标签: php sql join

我有两张桌子。一个存储内容记录,另一个存储内容记录之间的关系。

table "content"             table "relations"  
+---+-----+------+------+   +---------+----------+  
|id |num  |text  |value |   |id_local |id_foreign|  
+---+-----+------+------+   +---------+----------+  
|1  |111  |aaa   |12345 |   |2        |3         |  
+---+-----+------+------+   +---------+----------+  
|2  |222  |bbb   |23456 |   |2        |5         |  
+---+-----+------+------+   +---------+----------+  
|3  |333  |ccc   |34567 |   |4        |1         |  
+---+-----+------+------+   +---------+----------+  
|4  |444  |ddd   |45678 |   |2        |1         |  
+---+-----+------+------+   +---------+----------+  
|5  |555  |eee   |56789 |   |3        |6         |  
+---+-----+------+------+   +---------+----------+  
|6  |666  |fff   |67890 |   |4        |5         |  
+---+-----+------+------+   +---------+----------+  

阅读表“关系”

id_local =内容记录的id(“父”)
id_foreign =内容中与id_local(“child”)

相关的记录的id

我希望content.num = 222的所有关系按照它们在表“relations”中输入的顺序排列。结果应如下所示:

result  
+-----+------+  
|num  |value |  
+-----+------+  
|333  |34567 |  
+-----+------+  
|555  |56789 |  
+-----+------+  
|111  |12345 |  
+-----+------+  

我尝试了一些JOIN但从未得到过这样的结果。

拜托,有人知道我怎么能得到这个结果吗?

其他问题:

如果我想输出“parent”-record的content.value = 23456和所有“child”-records,查询应该如何?

result 2
+-----+------+--------+  
|num  |value | p-value|  
+-----+------+--------+
|333  |34567 | 23456  |  
+-----+------+--------+  
|555  |56789 | 23456  |    
+-----+------+--------+  
|111  |12345 | 23456  |  
+-----+------+--------+  

3 个答案:

答案 0 :(得分:1)

我猜这是奇怪的方法,但是;

SELECT num, value
FROM content
WHERE id IN (
  SELECT id_foreign
  FROM relations
  WHERE id_local = ( SELECT id FROM content WHERE num = '222' )
  )
  AND num = '222' -- Additional answer

答案 1 :(得分:0)

select  c2.num
,       c2.value
from    content c1
join    relations r
on      c1.id = r.id_local
join    content c2
on      r.id_foreign = c2.id
where   c1.num = 222

Example at SQL Fiddle.

答案 2 :(得分:0)

我在这里看不到join

您需要的只是“父”记录的ID ..在这种情况下,它是2

Select num, value from content where id in (select id_foreign where id_local=2)

如果您不知道ID,只知道num值......

Select num, value from content where id in (select id_foreign where id_local=(select id from content where num='222'))