数据库
首页 > 数据库> > MYSQL中的递归查询?

MYSQL中的递归查询?

作者:互联网

我认为我的问题可以通过“递归查询”解决,但是由于MySQL不支持递归查询,因此我尝试使用相邻列表模型.这应该不成问题,因为我知道我想走多深.

这是我需要做的一个例子:
表格类别:

dept    classNum    prereqDept  prereqClassNum
BIO     465         BIO         335
EE      405         EE          325
EE      325         EE          120
BIO     465         EE          120
BIO     335         BIO         225
BIO     225         CHEM        110
BIO     225         BIO         105

我需要的是某个级别(假设为400)的所有类,其所有先决条件最深为3个级别.
所以我会得到像

dept    classNum    prereqDept  prereqClassNum
BIO     465         BIO         335
BIO     465         BIO         225
BIO     465         CHEM        110
BIO     465         BIO         105
EE      405         EE          325
EE      405         EE          120
....

我知道如果我想深入3个级别,则需要使用3-LEFT JOIN,但是我不知道如何设置这些联接来获得所需的东西.
有任何想法吗?
我会感谢您的帮助!

附言我根本无法更改表结构.

解决方法:

嗯尝试这个:

SELECT * FROM
(
    (
        SELECT t1.dept, t1.classNum, t1.prereqDept, t1.prereqClassNum
        FROM class AS t1
        WHERE t1.classNum >= 400
    )
    UNION
    (
        SELECT t1.dept, t1.classNum, t2.prereqDept, t2.prereqClassNum
        FROM class AS t1
        JOIN class AS t2 ON (t1.prereqDept = t2.dept AND t1.prereqClassNum = t2.classNum)
        WHERE t1.classNum >= 400
    )
    UNION
    (
        SELECT t1.dept, t1.classNum, t3.prereqDept, t3.prereqClassNum
        FROM class AS t1
        JOIN class AS t2 ON (t1.prereqDept = t2.dept AND t1.prereqClassNum = t2.classNum)
        JOIN class AS t3 ON (t2.prereqDept = t3.dept AND t2.prereqClassNum = t3.classNum)
        WHERE t1.classNum >= 400
    )
) AS t4
ORDER BY dept, classNum, prereqDept, prereqClassNum

标签:recursive-query,sql,mysql
来源: https://codeday.me/bug/20191102/1989242.html