0

这可能很容易,但我没有足够的 mysql 经验,我有四个表:

  • 员工
  • 用户
  • 特权

我想从这四个表中选择以下内容:

  • 员工姓名
  • 用户身份
  • 计数(特权)
  • 计数(页)

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

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

但计数结果不正确,是相乘的

有任何想法吗?

4

2 回答 2

0

尝试:

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 
于 2015-07-06T10:40:29.140 回答
0

试试看-

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 
于 2015-07-06T10:41:52.563 回答