简体   繁体   中英

Using the result of query to get another result on the same table

I am struglling with this SQL query.

The following query returns me the v2_modules.id which I then want to run again on the v2_modules table to get all the rows who has got v2_modules.id as there parentId

select distinct v2_modules.id,v2_modules.name, v2_modules.url, v2_modules.parentId 
from v2_modules
            inner join v2_roles_permissions_modules
                on v2_modules.id =  v2_roles_permissions_modules.moduleId
                    inner join v2_admin_roles
                        on v2_roles_permissions_modules.roleId = v2_admin_roles.roleId
                            inner join admin
                                on v2_admin_roles.adminID = 89

I am struck here as to how should I get the reqired result.

You can wrap the result as a subquery, and do another join with the table:

select *
from
(
select distinct v2_modules.id,v2_modules.name, v2_modules.url, v2_modules.parentId 
from v2_modules
            inner join v2_roles_permissions_modules
                on v2_modules.id =  v2_roles_permissions_modules.moduleId
                    inner join v2_admin_roles
                        on v2_roles_permissions_modules.roleId = v2_admin_roles.roleId
                            inner join admin
                                on v2_admin_roles.adminID = 89
)
as table1
inner join v2_modules on v2_modules.parentId = table1.id

The join condition can be reversed, I don't know if it's the one you were looking for

like this?

select distinct 
    c.id,c.name, c.url, c.parentId 
from 
    v2_modules m    inner join
    (select distinct 
        m.id,m.name, m.url, m.parentId 
    from 
        v2_modules m    inner join 
        v2_roles_permissions_modules p  on 
        m.id =  p.moduleId
        inner join v2_admin_roles r on 
        p.roleId = r.roleId
        full outer join admin a
    where
        r.adminID = 89) c on
    m.parentid = c.id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM