PHP 中的 MySQL 递归查询替换 [英] MySQL recursive-query replacement in PHP

查看:73
本文介绍了PHP 中的 MySQL 递归查询替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于在 MySQL 中似乎无法进行递归查询,我想知道是否有解决方案可以获取相同的信息,同时限制我对数据库进行的查询次数.在我的情况下,我有相当于一棵树的东西,并给定了一个节点,我创建了一条返回根的路径,并在运行时保存节点的名称.给定一个这样的表:

Since it looks like recursive queries aren't possible in MySQL, I am wondering if there is a solution to get the same information that also limits the number of queries I make to the database. In my case I have what amounts to a tree and given a node, I make a path back to the root and save the name of the nodes as I go. Given a table like this:

 id | parent
-------------
 1  |   
 2  |   1
 3  |   1
 4  |   2
 5  |   2
 6  |   5

我想选择从 6 回到 1 (6,5,2,1) 的路径上的所有 id.由于路径的总长度未知,我认为唯一的方法是从一个查询中获取结果并构建一个新查询,直到我回到根.再说一次,我上次使用 MySQL 已经有几年了,所以如果我有点脱节,我也不会感到惊讶.任何帮助,将不胜感激.

I want to select all ids on the path from 6 back to 1 (6,5,2,1). Since the total length of the path is unknown I would assume that the only way to do this is taking the results from one query and build a new query until I am back at the root. Then again it has been a couple years since I last used MySQL so it wouldn't surprise me if I am a little out of touch. Any help would be appreciated.

推荐答案

因为它看起来在 mySQL 中不可能进行递归查询

Since it looks like recursive queries aren't possible in mySQL

mySQL 不支持 'CONNECT BY' 运算符,是的 - 但您可以使用 mysql 实现递归过程/函数并从中返回结果集.

mySQL doesn't support the 'CONNECT BY' operator, true - but you can implement recursive procedures/functions using mysql and return result sets from them.

这篇关于PHP 中的 MySQL 递归查询替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆