The problem with sql: I want to find out that Id is below 7 and all the standards for child nodes

this is my Structure (system) table

clipboard.png

Standard

clipboard.png

the relationship between the two tables is that the StructureID of the Standard table is equal to the Id field of the Structure
now I want to find out all the criteria of the Id below 7 and all the child nodes

ask for advice on what good methods there are no bosses. I thought of sql recursive query, but I"m not very good at it. Please give me some advice.

Mar.12,2021

step by step, first pick out the point with root node 7 in the Structure table:

SELECT GROUP_CONCAT(lv SEPARATOR ',') AS StructureIds
     FROM
       (SELECT @root:=
          (SELECT GROUP_CONCAT(id SEPARATOR ',')
           FROM STRUCTURE
           WHERE FIND_IN_SET(StructureParentId, @root)) AS lv
        FROM STRUCTURE
        JOIN
          (SELECT @root:=7) tmp
        UNION (SELECT 7)) a
;
The statement

is easy to understand, that is, starting from the first item of the table, each item is assigned once @ root, condition is that the parent node is in the previous @ root, and then you get the tmp table, and finally concatenate each @ root of the tmp table.

then you can take this string to the Standard table to query:

SELECT *
FROM Standard
WHERE StructureID IN
    (SELECT GROUP_CONCAT(lv SEPARATOR ',') AS StructureIds
     FROM
       (SELECT @root:=
          (SELECT GROUP_CONCAT(id SEPARATOR ',')
           FROM STRUCTURE
           WHERE FIND_IN_SET(StructureParentId, @root)) AS lv
        FROM STRUCTURE
        JOIN
          (SELECT @root:=1) tmp) a)
;
The important thing to note in

is the lookup function FIND_INT_SET.

try it. I hope it can help you.


WITH locs (id,StructureCode,StructureName,StructureParentId)

        AS
        (
        SELECT Id,StructureCode,StructureName,StructureParentId FROM Structure WHERE StructureParentId=$id
        UNION ALL
        SELECT A.id,A.StructureCode,A.StructureName,A.StructureParentId FROM Structure A,locs B ON A.StructureParentId = B.id
        )
        
        select s.Id , st.StructureCode,s.StandardName, s.StandardNumber , s.PublishDate,s.ImplementDate ,s.OldStandardNumber from 
        Standard s ,Structure st LEFT JOIN StdFile sf ON s.StandardNumber=sf.StandardNumber WHERE s.StructureID=$id OR s.StructureID IN (SELECT id FROM locs) group by s.Id 

the test data is as good as you want

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1bd1169-30d59.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1bd1169-30d59.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?