select 来自 4 个表的每个用户权限和页面的计数 mysql

select count of each user privileges and pages from 4 tables mysql

这可能很简单,但我对 mysql 没有足够的经验,我有四个表:

我想从这四个表中select以下:

所以我希望我的查询显示每个员工的用户名、授予的用户权限数和用户创建的页面数 我的表格结构如下:

CREATE TABLE IF NOT EXISTS `employee` (
  `ID` int(11) NOT NULL,
  `EMP_ENG_NAME_P1` varchar(15) DEFAULT NULL,
  `EMP_ENG_NAME_P2` varchar(15) DEFAULT NULL,) 
ALTER TABLE `employee`ADD PRIMARY KEY (`ID`);

CREATE TABLE IF NOT EXISTS `users` (
  `ID` int(11) NOT NULL,
  `USER_ID` varchar(30) DEFAULT NULL,
  `USER_EMP` int(11) DEFAULT NULL,) 
ALTER TABLE `users`ADD PRIMARY KEY (`ID`), 
  ADD UNIQUE KEY `USER_ID` (`USER_ID`), 
  ADD KEY `users_ibfk_1` (`USER_EMP`);

CREATE TABLE IF NOT EXISTS `privileg` (
  `ID` int(11) NOT NULL,
  `USER_ID` int(11) DEFAULT NULL,
  `PAGE_ID` int(11) DEFAULT NULL,)
ALTER TABLE `privileg`ADD PRIMARY KEY (`ID`);
ALTER TABLE `privileg` ADD CONSTRAINT `privileg_ibfk_2` 
  FOREIGN KEY (`USER_ID`) REFERENCES `users` (`ID`) 
  ON DELETE CASCADE ON UPDATE CASCADE;

CREATE TABLE IF NOT EXISTS `pages` (
  `ID` int(11) NOT NULL,
  `userCreatorID` int(11) DEFAULT NULL,
  `PAGE_ENG_DESC` varchar(100) DEFAULT NULL,)

我能够构建两个显示相同结果的查询,一次使用每个用户的权限计数,一次使用每个用户的页数 第一次查询:

select employee.EMP_ENG_NAME_P1, employee.EMP_ENG_NAME_P2, users.USER_ID, COUNT(privileg.ID)
from employee
  INNER JOIN users on users.USER_EMP = employee.EMP_ID
  INNER JOIN privileg on users.ID= privileg.USER_ID
GROUP BY users.ID 

第二个查询:

select employee.EMP_ENG_NAME_P1, employee.EMP_ENG_NAME_P2, users.USER_ID, users.ID, COUNT(pages.ID)
from employee
  INNER JOIN users on users.USER_EMP = employee.EMP_ID
  INNER JOIN pages on users.ID = pages.userCreatorID
GROUP BY users.ID

我现在需要的是将它们组合在一起,如下图 我使用以下查询:

select employee.EMP_ENG_NAME_P1,employee.EMP_ENG_NAME_P2, users.USER_ID, users.ID, COUNT(pages.ID), COUNT(privileg.ID) 
from employee 
INNER JOIN users on users.USER_EMP=employee.EMP_ID 
INNER JOIN privileg on users.ID= privileg.USER_ID 
INNER JOIN pages on users.ID= pages.userCreatorID 
GROUP BY users.ID

但计数结果不正确,相乘

有什么想法吗?

尝试:

SELECT employee.EMP_ENG_NAME_P1, employee.EMP_ENG_NAME_P2, users.USER_ID, COUNT(privileg.ID), COUNT(pages.ID)
FROM employee
  INNER JOIN users on users.USER_EMP = employee.EMP_ID
  INNER JOIN privileg on users.ID= privileg.USER_ID
  INNER JOIN pages on users.ID = pages.userCreatorID
GROUP BY users.ID 

试一试-

SELECT emp.EMP_ENG_NAME_P1, emp.EMP_ENG_NAME_P2, usr.USER_ID, COUNT(DISTINCT prv.ID), COUNT(DISTINCT pgs.id)
FROM employee emp 
INNER JOIN users usr ON usr.USER_EMP = emp.EMP_ID 
INNER JOIN privileg prv ON usr.ID= prv.USER_ID 
INNER JOIN pages pgs ON usr.ID= pgs.UserCreatorID  
GROUP BY users.ID