【问题标题】:Get related rows in one table using a table with relations使用具有关系的表获取一个表中的相关行
【发布时间】:2013-05-18 11:33:52
【问题描述】:

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

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 的所有关系按照它们在表“关系”中输入的顺序。结果应如下所示:

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  |  
+-----+------+--------+  

【问题讨论】:

  • 您使用的是哪个数据库? (MySQL、SQL Server、Oracle 等)
  • 对不起,datavase 是 MySQL-

标签: php sql join


【解决方案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

【讨论】:

  • 错了。 id_local 将是 2 而不是 222
  • 这给了我一个错误代码子查询返回不止一行
  • 如果您的 num 字段不是整数,则使用 '222'
  • 我添加了一个附加问题。请看一下。
  • 可以在查询结尾添加AND num = '222';再看我的回答
【解决方案2】:
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.

【讨论】:

  • 这给了我一个结果,列出 content.num, content.value for content.id=2 3 次(父记录),但不是三个相关记录。
  • 该查询确实在 SQL Fiddle 上产生了 3 条相关记录
【解决方案3】:

我认为这里不需要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'))

【讨论】:

  • 非常感谢。按下 ENTER 键后就有这么多好的答案。
  • 太好了 - 希望这会有所帮助。编码快乐!
  • 这给了我一个错误代码“子查询返回多于一行”
猜你喜欢
  • 2010-10-13
  • 1970-01-01
  • 1970-01-01
  • 2014-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-10
相关资源
最近更新 更多