我有两个表:线和点。线表表示两点之间的互连。线表具有: idLine idStartPoint idEndPoint ... YL19197 YP004990 YP004991 YL19195 YP004989 YP004990 YL19199 YP004991 YP004992 ...积分表具有: idPoint Feed ... YP004990 0 YP004989 0 YP004991 0 ....... ... YP005214 1仅具有idLine值,我需要遍历基于idStartPoint和idEndPoint的所有行,直到有一个提要值为“ 1”的点。现在,我这样做了(假设idLine为YL19197)搜索YL19197行,并带idStartPoint(YP004990)和idEndPoint(YP004991)生成一个查询,该查询将带到YL19197的两条线连接起来(不带回YL19197): 从idStartPoint ='YP004990'和idLine 的行中选择* 'YL19197' 从idEndPoint ='YP004990'和idLine 的行中并选择* 'YL19197' 从idStartPoint ='YP004991'和idLine的行并选择* 'YL19197' 从idEndPoint ='YP004991'和idLine 的行中并选择* 'YL19197'这使我回到两行:idLine idStartPoint idEndPointYL19195 YP004989 YP004990YL19199 YP004991 YP004992但是,我需要所有互连的线,直到找到一条指向“ feed = 1”的线。图示: (adsbygoogle = window.adsbygoogle || []).push({}); 最佳答案 MySQL直到8.0.1版才支持递归查询。这应该工作:WITH RECURSIVE r(idLine, idStartPoint, idEndPoint) AS ( SELECT idLine, idStartPoint, idEndPoint FROM line WHERE idLine='YL19197' UNION ALL SELECT l.idLine, l.idStartPoint, l.idEndPoint FROM r JOIN line l ON l.idStartPoint = r.idEndPoint JOIN points p ON p.idPoint = r.idEndPoint WHERE p.feed = 0)SELECT * FROM r;输出您应该在问题中输入的数据:+---------+--------------+------------+| idLine | idStartPoint | idEndPoint |+---------+--------------+------------+| YL19197 | YP004990 | YP004991 || YL19199 | YP004991 | YP004992 |+---------+--------------+------------+您的测试数据看起来没有足够的行来证明在feed = 1时终止。如果您使用的MySQL版本低于8.0.1,则必须采用另一种方法。最简单的方法是编写应用程序代码以对一行运行一个查询,然后检查结果是否是您要查找的终点,如果不是,则循环并为下一行进行另一个查询。 (adsbygoogle = window.adsbygoogle || []).push({}); 10-07 22:49