用一條sql查詢出選單數以及選單對應的角色關係

2021-08-22 06:07:09 字數 1954 閱讀 3247

前幾天公司要求將系統選單樹以及選單對應的角色關係列出來做調整,所以寫了如下sql供參考

select tt.t1 一級選單, tt.t2 二級選單, tt.t3 **選單, tt.t4 四級選單, group_concat(rel.role_code) 選單角色

from (select m1.menu_name t1, m2.menu_name t2, m3.menu_name t3, m4.menu_name t4,

(case

when m4.parent_code is null

then case

when m3.parent_code is null

then m2.parent_code -- 從最後一級選單往上匹配沒有parent_code的選單(這裡到二級選單結束)

else m3.parent_code

end

else m4.parent_code

end) code

from menu_test m1

left join menu_test m2 on m1.menu_code = m2.parent_code

left join menu_test m3 on m2.menu_code = m3.parent_code

left join menu_test m4 on m3.menu_code = m4.parent_code -- 這裡有幾級選單就關聯幾個

where m1.level = '1' ) tt , -- 從一級選單開始往下查詢

role_meun_rel rel

where tt.code = rel.menu_code

group by tt.t1, tt.t2, tt.t3, tt.t4

查詢效果如下:

一級選單

二級選單

**選單

四級選單

選單角色

一級選單

二級選單(1)

xx10,xx20,xx30,xx99

一級選單

二級選單(2)

**選單(2)(1)

xx20,xx99

一級選單

二級選單(3)

**選單(3)(1)

四級選單(3)(1)(1)

xx30,xx99

create table menu_test (

`menu_code` varchar(10) character not null comment '選單編碼',

`level` varchar(2) character default null comment '選單級別',

`parent_code` varchar(10) character default null comment '父選單編碼',

`menu_name` varchar(20) character default null comment '選單名稱',

primary key (`menu_code`)

) comment='選單表';

create table `role_meun_rel` (

`role_code` varchar(20) character default null comment '角色編碼',

`menu_code` varchar(20) default null comment '選單編碼',

unique key `role_menu_index` (`role_code`,`menu_code`)

) comment='角色與選單關係表';

SQL查詢當前資料以及上一條和下一條三條記錄

想查詢某個表當前資料以及上一條和下一條的記錄,網上找了一下解決辦法都不如意,按網上的方法可以查詢出三條資料,但是當查詢的這條資料沒有上一條或下一條記錄時就不行了。現在我把解決問題的sql語句放上 理一下思路,明確的查詢三條語句 select from 表名 where id in 當前id的前乙個i...

查詢 新增 修改 一條sql 搞定

1 不存在,則新增 不會自動修改 insert into king wz yname,title select 42 北京 from dual where not exists select id from king wz where yname 42 語句解析 select not exists ...

SQL查詢當前資料上一條和下一條的記錄

id是指當前資料news id引數 方法一 string presql select top 1 from news where news id id order by news id desc string nextsql select top 1 from news where news id ...