mysqlsqljoincountmulti-query

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


This might be easy but I don't have enough experience with mysql, I have four tables:

I want to select from these four tables the following:

so I want my query to display each employee user name, number of granted user privileges and number of pages created by the user my tables structure goes as follows:

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,)

I was able to construct two queries that display the the same result seperated once with the privilege count for each user and once with the page count for each user first query:

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 

second query:

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

What I need now is to combine them together,like the following image enter image description here I use the following query:

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

but the count result is not correct, it is multiplied

any ideas?


Solution

  • try it-

    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