我应该执行什么 SQL 查询才能获得预期的结果集?
我应该执行什么 SQL 查询才能获得预期的结果集,将链的第一个元素 (2) 作为输入数据或其中任何一个?
table name: changes
+----+---------------+---------------+
| id | new_record_id | old_record_id |
+----+---------------+---------------+
| 1| 4| 2|
| -- non relevant data -- |
| 6| 7| 4|
| -- non relevant data -- |
| 11| 13| 7|
| 12| 14| 13|
| -- non relevant data -- |
| 31| 20| 14|
+----+---------------+---------------+
Result set expected:
+--+
| 2|
| 4|
| 7|
|13|
|14|
|20|
+--+
我知道我应该考虑更改我的数据模型,但是:如果我不能怎么办?
先感谢您!
What SQL query should I perform to get the result set expected, giving the first element of the chain (2) as input data, or any of them ?
table name: changes
+----+---------------+---------------+
| id | new_record_id | old_record_id |
+----+---------------+---------------+
| 1| 4| 2|
| -- non relevant data -- |
| 6| 7| 4|
| -- non relevant data -- |
| 11| 13| 7|
| 12| 14| 13|
| -- non relevant data -- |
| 31| 20| 14|
+----+---------------+---------------+
Result set expected:
+--+
| 2|
| 4|
| 7|
|13|
|14|
|20|
+--+
I know I should consider change my data model, but: What if I couldn't?
Thank you in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
以下代码应该可以得到你的结果
Following code should work to get your result
由于您对数据库不清楚,这里有一些很好的文献:
MySQL
看看第 7 节,这涉及层次结构和递归函数
http://www.artfulsoftware.com/mysqlbook/sampler/mysqled1ch20.html
MSSQL
关于同一件事的好文章(您将发现函数的共同之处,尽管 MSSQL 可以使用WITH)。
http://www.sqlservercurry.com/2009/06 /simple-family-tree-query-using.html
PostgreSQL
相同类型的文章。所有这些都有相同的前提,从子级到父级沿着数据库树向上工作。
http://www.paragoncorporation.com/ArticleDetail.aspx?ArticleID=24
Since you're vague on the database, here is some good literature:
MySQL
Look around section 7, this goes in to hierarchy and recursive functions
http://www.artfulsoftware.com/mysqlbook/sampler/mysqled1ch20.html
MSSQL
Good article on the same thing (you're going to find functions the common place, though MSSQL can use WITH).
http://www.sqlservercurry.com/2009/06/simple-family-tree-query-using.html
PostgreSQL
Same type of article. All these have the same premise, working your way up a database tree from child to parent.
http://www.paragoncorporation.com/ArticleDetail.aspx?ArticleID=24
如果您不想更新中间的数据,那么唯一的解决方案是
但是如果它按照出现的顺序进行更新,则此更新可能会起作用,如果您将表的 pk 设置为 id,通常会发生这种情况。
您还可以通过在末尾添加
order by i
d 来强制执行此操作,并让您查看是否允许这样做。if you have data in the middle that you do not want to update then the only solution would be
But this update might work if it does the updates in the order they appear which will generally happens if you have the pk of the table set to id.
You can also force this by adding an
order by i
d at the end, and let you see if it allows that.