0

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,其中没有一个客户端可以有一个等于给定输入 ($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 才能触发 <>。我希望这是有道理的?

我会通过分组来解决这个问题吗?如果声明?

编辑:

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
4

1 回答 1

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;
于 2013-01-16T07:46:56.813 回答