Sqlfiddle is http://sqlfiddle.com/#!2/7df50/4
Basically, I have 3 tables: group, membership, client.
tbl.client = client_id (PK, AI), industry_id (FK), status
tbl.membership = membership_id (PK, AI), Client_id (FK to tbl.client),
group_id (FK to group), status
tbl.group = group_id (PK, AI), target_market_id (FK), geography_id (FK)
Basically, I want to select a group_id by joining all 3 tables where NONE of the clients can have a client.industry_id equal to a given input ($client_industry_id).
My query so far is:
"select g.group_id from `group` g join membership m on m.group_id=g.group_id ".
"join client c on c.client_id=m.client_id ".
"where g.status=1 and m.status=1 and c.status=1 and ".
"g.geography_id=$target_geography and ".
"g.target_market_id=$target_market ".
"c.industry_id <> $client_industry_id";
The problem with the query is that it will still select a group_id from group because ALL clients must not have a client_id = $client_industry_id in order to trip the <>. I hope that makes sense?
Would I solve this problem via grouping? If statement?
EDIT:
insert into client (email, industry_id, status) VALUES ('email1@gmail.com', '1', '1')
insert into client (email, industry_id, status) VALUES ('email2@gmail.com', '2', '1')
insert into client (email, industry_id, status) VALUES ('email3@gmail.com', '2', '1')
insert into membership (client_id, group_id) VALUES (1, 1)
insert into membership (client_id, group_id) VALUES (2, 1)
insert into membership (client_id, group_id) VALUES (3, 2)
insert into group (geography_id, target_market_id) VALUES (1, 1)
insert into group (geography_id, target_market_id) VALUES (1, 1)
#psuedo code
"select group_id from group join membership on group_id, join client on client_id where
all status=1 and group.geography_id=1 and group.target_market_id=1 and
NONE of the clients have client.industry_id=1
-- query should result in group_id=2
You and @Strawberry are right, the previous code couldn’t have worked. Sorry about that. And Here’s a quick crack at what you might want to try instead: