mysql - 如何使用存储过程或数据透视表选择来操作我的数据库数据?
问题描述
我的数据库中有三个表。用户、应用程序和应用程序访问表,该表将应用程序与用户配对以表示用户对所述应用程序的访问。
Create table applications (
id int,
app_name varchar(45) not null unique,
app_link varchar(70),
description varchar(400),
primary key (id)
);
create table users (
id int,
windows_id varchar(25) not null unique,
full_name varchar(50),
user_role int,
email char(50),
is_active int,
primary key (id)
);
create table app_access (
user_id int,
app_id int,
app_name varchar(30),
primary key(user_id, app_id),
constraint app_fk foreign key (app_id)
references applications(id),
constraint user_fk foreign key (user_id)
references users(id)
);
我希望能够创建一个 select 语句,它将从我当前的表中生成一个如下所示的表:
当前表:
在上面的数据中,john 可以访问这两个应用程序,而 bob 只能访问 byewrld。
我想从 sql select 语句中得到这样的表:
我可以在我的表格设计中硬编码这些值(每个应用程序作为一列),但应用程序和用户的列表正在增长,我希望能够看到用户对应用程序的访问,如上所示。
解决方案
试试这个,所以这将显示基于新应用程序创建的顺序
delimiter $$
create procedure sp_app_user()
begin
select group_concat(concat("sum(if(aa.app_name ='",app_name,"',1,0)) '",app_name,"'")) into @pivotcol
from (select app_name from applications group by app_name order by id) t;
set @pivotquery =concat('select u.id, ',@pivotcol,' from app_access aa
join users u on aa.user_id=u.id
join applications a on aa.app_id=a.id
group by u.id;');
prepare stmt from @pivotquery;
execute stmt;
deallocate prepare stmt;
end $$
delimiter ;
推荐阅读
- c# - Sitecore 9 如何建立基于声明的 Active Directory 授权
- python - 第 2 页上的下一个按钮 XPath 更改,不会循环
- shell - Shell:如何确定文本文件中的行长度不超过 2048 字节
- php - 相同结构但数量不同的单词的正则表达式(计数)
- generics - 为什么在使用嵌套泛型创建枚举时会出现“溢出”错误?
- python - 为 TensorFlow CNN 改变 MNIST 的形状
- c# - Prism WPF:如何打开新窗口/对话框
- java - 程序接口 - 但在实现上使用自定义方法
- linux - 使用 cron 执行时,bash 脚本无法按预期工作
- android - Oreo (API 26) 应用程序在后台时未收到通知