Sqlfiddle是http://sqlfiddle.com/#!2/7df50/4
基本上,我有3个表:组,成员,客户。
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)
基本上,我想通过连接所有3个表来选择group_id,其中NONE客户端的client.industry_id等于给定的输入($ client_industry_id)。
到目前为止,我的查询是:
"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";
查询的问题在于它仍然会从组中选择group_id,因为所有客户端都必须没有client_id = $ client_industry_id才能使&lt;&gt;跳转。我希望这有道理吗?
我会通过分组来解决这个问题吗?如果声明?
编辑:
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
答案 0 :(得分:1)
你和@Strawberry是对的,以前的代码是行不通的。对于那个很抱歉。以下是您可能想要尝试的快速解决方案:
select g.group_id from groupp g
join membership m on m.group_id=g.group_id and m.status=1 //to consider check on status
join client c on c.client_id=m.client_id and c.status=1 //to consider check on status
where g.group_id not in (select mm.group_id from membership mm join client cc on mm.client_id=cc.client_id and cc.industry_id = $client_industry_id) and //to exclude groups with clients that have industry
g.status=1 and
g.geography_id=$target_geography and
g.target_market_id=$target_market;