我希望有每个角色的总用户类型角色行动。
这是我的表:
t_users : id_user, username, userpass, status, ...
t_action: id_action, id_user, id_role, id_type_role, ...
t_role: id_role, libelle, status
t_type_role: id_type_role, libelle, status
这是我的数据:
INSERT INTO `t_users` (`id_user`, `username`, `password`, `status`) VALUES
(1, 'foo', 'pass1', '1'),
(2, 'bar', 'pass2', '0'),
(3, 'fusion', 'pass3', '2');
INSERT INTO `t_role` (`id_role`, `libelle`, `statut`) VALUES
(1, 'Operator', 1),
(2, 'User', 1),
(5, 'Administrator', 1);
INSERT INTO `t_type_role` (`id_type_role`, `libelle`, `statut`) VALUES
(1, 'Executif', 1),
(2, 'home', 1),
(3, 'System', 1);
INSERT INTO `t_action` (`id_action`, `id_user`, `id_role`, `id_type_role`) VALUES
(1, 1, 5, 3),
(2, 2, 5, 3);
预期结果:
-
第一个解决方案:
根据另一位用户在评论中的建议,我写了这样的单个查询:
SELECT DISTINCT
R.libelle ROLE,
COUNT( IF( T.libelle= 'Executif', 1, NULL )) AS Executif,
COUNT( IF( T.libelle= 'Home', 1, NULL )) AS Home,
COUNT( IF( T.libelle= 'System', 1, NULL )) AS System
FROM t_users U
JOIN t_action A ON A.id_user = U.id_user
JOIN t_role R ON R.id_role = A.id_role
JOIN t_type_role T ON T.id_type_role = A.id_type_role
GROUP BY ROLE
可以正常工作。
但是如果再添加一个COUNT条件呢?动态吗?
:
thisconditions应该是动态构建的。因为它们是基于表T.libelle的,它可以按时增长。
示例如果我们向t.l ebelle添加了一个新值,那么根据CONDITIONS的语法,查询必须包含这个新值。
,CONDITIONS = COUNT( IF( T.libelle= 'Executif', 1, NULL )) AS Executif,
COUNT( IF( T.libelle= 'Home', 1, NULL )) AS Home,
COUNT( IF( T.libelle= 'System', 1, NULL )) AS System
CONDITIONS = COUNT( IF( T.libelle= 'Executif', 1, NULL )) AS Executif,
COUNT( IF( T.libelle= 'Home', 1, NULL )) AS Home,
COUNT( IF( T.libelle= 'System', 1, NULL )) AS System
COUNT( IF( T.libelle= 'New_libelle', 1, NULL )) AS New_libelle