Vegard Berg Vegard Berg - 2 months ago 7
MySQL Question

Condition LEFT JOIN MYSQL PHP

I want to add a condition to my left join MySQL query.
Each project that is created, is maintained by a administrator. This administrator should see how many users there is total in his projects(not all users in every project that is exists). When a project is created, the administrator ID is saved in the table cms_prosjekt.

This is my query so far:

$result = mysql_query("SELECT users.motto, COUNT( * ) AS count FROM users
WHERE id = '".$_SESSION['user']['id']."' //<- admins inlogged ID
LEFT JOIN cms_prosjekt ON users.motto=cms_prosjekt.code
GROUP BY users.motto");


Users table have a Unique ID for each user, cms_projeckt have a column for userid.

Users table
https://i.gyazo.com/c733944956f82f16989c5c5ddfc86e74.png

cms_prosjekt
https://i.gyazo.com/0179c47ec9508931e3a8f7eb0edbab95.png

Answer

Where condition should be after Joins.

$result = mysql_query("SELECT users.motto, COUNT( * ) AS count FROM  users 
LEFT JOIN cms_prosjekt ON  users.motto=cms_prosjekt.code 
WHERE cms_prosjekt.id = '".$_SESSION['user']['id']."' //<- admins inlogged ID
GROUP BY  users.motto");