Answer the question
In order to leave comments, you need to log in
MYSQL fetch from same table?
Hello.
It was necessary to select the number of objects for each user, such a request could be formulated:
$statement = $connection->prepare("SELECT DISTINCT(usr.name), usr.id, c.cnt, d.excnt FROM users usr
LEFT JOIN (SELECT COUNT(*) as cnt, obj.realtor_id FROM objects obj GROUP BY realtor_id) as c ON usr.id=c.realtor_id
LEFT JOIN (SELECT COUNT(*) as excnt, obj.realtor_id FROM objects obj WHERE obj.exclusive=1 GROUP BY realtor_id) as d ON usr.id=d.realtor_id");
$statement = $connection->prepare("SELECT DISTINCT(usr1.name), usr1.id, c.cnt, d.excnt FROM users usr1
LEFT JOIN (SELECT usr.id, usr.manager_id FROM users usr) as b ON usr1.id=b.manager_id
INNER JOIN (SELECT COUNT(*) as cnt, obj.realtor_id FROM objects obj GROUP BY realtor_id) as c ON b.id=c.realtor_id
INNER JOIN (SELECT COUNT(*) as excnt, obj.realtor_id FROM objects obj WHERE obj.exclusive=1 GROUP BY realtor_id) as d ON b.id=d.realtor_id");
Answer the question
In order to leave comments, you need to log in
It is difficult to understand the structure and logic of the work, but I will try to assume that the managerId field in the users table will be null for managers.
SELECT USR1.NAME,
USR1.ID,
C.CNT,
D.EXCNT
FROM USERS USR1
LEFT JOIN (SELECT COUNT (*) AS CNT, OBJ.REALTOR_ID
FROM OBJECTS OBJ
GROUP BY REALTOR_ID) AS C ON USR.ID = C.REALTOR_ID
LEFT JOIN (SELECT COUNT (*) AS EXCNT, OBJ.REALTOR_ID
FROM OBJECTS OBJ WHERE OBJ.EXCLUSIVE = 1
GROUP BY REALTOR_ID) AS D ON USR.ID = D.REALTOR_ID;
WHERE MANAGER_ID IS NULL
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question