1

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

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 相关的内容中的记录 ID(“子级”)

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

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

我尝试了一些 JOIN,但从未得到这个结果。

请问,有人知道我怎样才能得到这个结果吗?

附加问题:

如果我想输出带有所有“子”记录的“父”记录的 content.value=23456,查询应该是什么样子?

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

3 回答 3

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
于 2013-05-18T11:38:49.240 回答
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

SQL Fiddle 的示例。

于 2013-05-18T11:36:22.180 回答
0

我认为join这里不需要 a 。

您所需要的只是“父”记录的 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'))

于 2013-05-18T11:39:17.340 回答