2014-02-10 13 views
0

多個值,我有以下SQL:檢查,如果有一列中

SELECT DISTINCT cp_pessoa.id, cp_pessoa.nome 
    FROM cp_pessoa 
LEFT JOIN cp_habilidade_freelancer ON (cp_habilidade_freelancer.id_freelancer = cp_pessoa.id) 
LEFT JOIN cp_habilidade ON (cp_habilidade.id = cp_habilidade_freelancer.id_habilidade) 
    WHERE cp_habilidade.id = 71 OR cp_habilidade.id = 695 
LIMIT 0, 10 

我只希望人們(cp_pessoa)誰擁有所有的技能(71,695)。

它可能看起來簡單,但我掙扎。

例子:

如果我使用或下面的人有以下技能(1,2,71)返回(人沒有能力695) 如果我使用並與以下技能下面的人( 71,695)不返回

謝謝!

+0

有些言論以自己的查詢:1. SELECT DISTINCT是很經常的壞查詢標誌 - 選擇重複,然後你需要刪除它們。你爲什麼要加入外部?你只需要擁有這些技能的自由職業者,那麼爲什麼包括那些不是自由職業者的人,爲什麼包括那些沒有所需技能的自由職業者呢? where子句再次刪除所有這些記錄。當cp_habilidade_freelancer.id_habilidade已經包含你正在尋找的信息時,你甚至爲什麼加入cp_habilidade? –

+0

@ThorstenKettner查詢是一塊其他 – user4919

回答

1

這是功課?如果是這樣,這個想法應該足夠了:你正在尋找那些關聯技能71和695的數量是2的人。

如果這不是家庭作業,但是一個真實的任務,那麼告訴我,我會給你:-)

編輯完整的SQL語句:直進的辦法是問,如果一個人同時存在的技能:

select id, nome 
from cp_pessoa p 
where exists 
(
    select * 
    from cp_habilidade_freelancer hf 
    where hf.id_freelancer = p.id 
    and hf.id_habilidade = 71 
) 
and exists 
(
    select * 
    from cp_habilidade_freelancer hf 
    where hf.id_freelancer = p.id 
    and hf.id_habilidade = 695 
); 

與查詢cp_habilidade_freelancer只有一次的另一種方式:

select id, nome 
from cp_pessoa p 
where id in 
(
    select id_freelancer 
    from cp_habilidade_freelancer hf 
    where id_habilidade in (71, 695) 
    group by id_freelancer 
    having count(distinct id_habilidade) = 2 
); 

你可以改變計數(不同id_habilidade)的情況下COUNT(*),可以保證有在cp_habilidade_freelancer的id_freelancer沒有重複的技能。

+0

這是一個真正的任務:) – user4919

+0

好。從你對另一個答案的評論中,我瞭解到你不是在尋找「同時擁有技能71和695的人」,而是「擁有技能71和695但沒有其他技能的人」。正確? –

+0

不,不可以,這個人可以有其他技能,但71和695是強制性的 – user4919

相關問題