2013-01-16 25 views
0

Sqlfiddle是http://sqlfiddle.com/#!2/7df50/4MySQL查詢:選擇GROUP_ID但如果所述組中的任何的client_id是= X然後不選擇

基本上,我有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 ('[email protected]', '1', '1') 
insert into client (email, industry_id, status) VALUES ('[email protected]', '2', '1') 
insert into client (email, industry_id, status) VALUES ('[email protected]', '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

解釋與樣本輸入數據和輸出數據 –

+0

如果我理解這個正確的,你要選擇其中客戶端不屬於輸入產業集團。如我錯了請糾正我。 嘗試在連接子句中移動「c.industry_id <> $ client_industry_id」,例如「在c.client_id = m.client_id和c.industry_id <>上添加客戶端c」,$ client_industry_id「 – uchamp

+0

」更新了該部分。 @uchamp我會把它放在where子句中嗎? –

回答

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; 
+0

其實,這不起作用。我有一個不好的數據集。它仍然顯示有c.industry_id = XXX的客戶 –