2016-08-07 9 views
0

私はより良い方法を複数回

AnimalId Feature Present 
-------- ------- ------- 
1   Teeth Yes 
1   Leg  Yes 
2   Teeth No 
2   Leg  Yes 
3   Teeth Yes 
3   Leg  Yes 

下記の構造を持つテーブルの動物を持って、両方の歯とレージュは私が書かれている「はい」 ある場合、私はanimalidを取得する必要があります


select distinct A1.AnimalId from Animal A1 
inner join Animal A2 on 
A1.AnimalId = 
(select distinct A2.AnimalId from Animal A2 
inner join Animal A3 on 
A2.AnimalId = 
(select distinct A3.AnimalId from Animal A3 where A3.Feature = 'Leg' and A3.Present = 'Yes' group by A3.AnimalId) 
where A2.Feature = 'Teeth' and A2.Present = 'Yes' group by A2.AnimalId) 

とその作業のようなクエリ。

これを書き、同じ結果を達成するためのより良い方法がありますか?

+0

なぜあなたは全く参加している:?

select a.animalId from animal a where (a.feature = 'Teeth' and a.present = 'Yes') or (a.feature = 'Leg' and a.present = 'Yes') group by a.animalId having count(distinct a.feature) = 2; 

where句は、に簡素化することができますかテーブルを照会して "where"節を使用するだけです... –

+1

恐ろしいEAV([エンティティ属性値モデル](https://en.wikipedia.org/wiki/Entity%E2%80%93attribute%E2%80)に注意してください%93value_model));これは一般的に、あなたが見つけたように、大変な質問をしています。 –

答えて

2

group byhavingを使用してこのタイプのクエリにアプローチしたいと思います。あなたのケースでは:

where a.feature in ('Teeth', 'Leg') and a.present = 'Yes' 
+0

質問していただきありがとうございます..私は鼻や耳のようないくつかの機能を持っていますが、脚と歯の両方が存在する必要がありますが、鼻または耳のいずれかがある可能性があります。 ( "歯"、 "脚"、 "'、' '、' '、' '、' ')およびa.present ='の特徴を動物から選択して、はい) 及び( (a.feature = '鼻' とa.Present = 'いいえ') 又は(a.feature = '耳' とa.Present = 'いいえ') \t)によって 基.animalId カウント(別名a.feature)= 4; "。しかし、それはどのようなアイデアyを働かない? –

+0

ありがとう..働いています..動物からのa.animalId を選択するように変更しました ここで、( 'Teeth'、 'Leg'、 ''、 ''、 ''、 ''、 ''、 (a.feature = 'Nose'とa.Present = 'No')または(a.feature = 'Nose'とa.Present = 'Yes')) (a.feature = '耳'とa.Present = 'いいえ'または(a.feature = '鼻'とa.Present = 'はい'))\t グループby a.animalId count(別名a。特徴)= 4; –

+0

これには2つの側面があります。実際のクエリの保守性(または構文優先)とクエリのパフォーマンスです。 1つのフォームはあなたに良く見えるかもしれませんが、悪いことに実行するか、逆もあります。もう1つのオプションは 'EXISTS'を使用し、これはより良いか悪いかを実行するかもしれませんし、多かれ少なかれ保守可能かもしれません。クエリーが多かれ少なかれ作業を行うということを別の方法で書いているので、クエリープランだけがそれを伝えているとは思わないでください。 –

関連する問題