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)

基本的に、特定の入力 ($client_industry_id) と等しい client.industry_id を持つクライアントが存在しない 3 つのテーブルすべてを結合して、group_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";

クエリの問題は、<> をトリップするために、すべてのクライアントが client_id = $client_industry_id を持つ必要がないため、グループから group_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 に答える