I have a database table called ‘members‘. Assigned to members is a position.
Positions come from Departments. I have Departments, then Sub-Departments within those and Positions within the Sub-Departments.
Hopefully I haven’t lost you.
What I want to do is is select all the members within a department, excluding any of those members from one position within that department.
“departments” Table: (includes departments and sub-departments)
ID NAME PARENT_ID
1 Department #1 NULL
2 Department #2 NULL
3 Sub Department #1 1
4 Sub Department #2 1
5 Sub Department #3 2
“departments_positions” Table:
ID NAME SUB_DEPARTMENT_ID
1 Position #1 3
2 Position #2 3
3 Position #3 4
“members_positions” Table:
ID MEMBER_ID POSITION_ID
1 1 1
2 1 2
3 1 3
Here’s my MySQL code:
SELECT m.* FROM members AS m
LEFT JOIN members_positions AS mp ON mp.member_id = m.id
LEFT JOIN departments_positions AS dp ON mp.position_id = dp.id
LEFT JOIN departments AS sd ON dp.sub_department_id = sd.id
LEFT JOIN departments AS d ON sd.parent_id = d.id
WHERE mp.position_id != '2' AND d.id = '1'
GROUP BY m.id
So as you can see I want to extract the members that are in “Department #1” (ID: 1 from departments_table) but not members who are in Position #2 (ID: 2 from departments_positions table) of that department.
Hopefully I am making sense. My code above doesn’t seem to work. It just exports everyone from the department.
It’s because you are using LEFT JOIN, which will not filter data.
Change your query to use INNER JOIN.
You also cannot use a select * if you’re grouping by member id.
Edit: I inputed your tables into a local mysql db and confirmed this query working.
Also, any reason why you’re quoting your int values 2 & 1 in the where statement?
If you only want the unique member id’s, you don’t need to do a
GROUP BY. You should switch your select to this and then use an outer select to get all the member info: