2017-04-03 13 views
0

は、私はこのような学生のテーブルを持って考えてみましょう:動的な属性名検索

student_id name address ... school employer 
    1  Chris 2 John   UofJ  J Limited 
    2  Ann  3 Doe   UofD  D limited 

今私はschool = 'UofJ'employer = 'J Limited'を持っている学生のリストを見つける必要があります。簡単:

student_attribute_id student_id attribute_name attribute_value 
     1     1   school   UofJ 
     1     1   company   J Limited 
     1     2   school   UofD 
     1     2   company   D Limited 

私のタスクがリストを見つけることです:

select * from student where school = 'UofJ' and employer = 'J Limited' 

しかし、私の現実は、最後の2つの属性が列として学生のテーブルに格納されているが、別のテーブルに行としてstudent_attributeと呼ばれていますこのstudent_attributeテーブルの生徒IDは、依然としてschool = 'UofJ'employer = 'J Limited'に基づいています。私はどうすればいいのですか?

さらに、私はSpringboot JPSリポジトリを使用してクエリを実行していますので、SQLの方法またはJPAの方法の両方を解決することに喜んでいます。それぞれの参加を設定

+0

ATTRIBUTE_VALUEは異なる型を含む文字列ですか?あなたは常に文字列を検索していますか?また数字と日付を検索する必要がありますか? –

答えて

2

あなたは真の条件の両方を持っているSTUDENT_IDを見つけるために、条件付き集約を使用することができます。

select student_id 
from student_attribute 
group by student_id 
having count(case 
      when attribute_name = 'school' 
       and attribute_value = 'UofJ' 
       then 1 
      end) > 0 
    and count(case 
      when attribute_name = 'company' 
       and attribute_value = 'J Limited' 
       then 1 
      end) > 0 

これをStudentテーブルと組み合わせて、対応する詳細を取得できます。

select s.* 
from student s 
join (
    select student_id 
    from student_attribute 
    group by student_id 
    having count(case 
       when attribute_name = 'school' 
        and attribute_value = 'UofJ' 
        then 1 
       end) > 0 
     and count(case 
       when attribute_name = 'company' 
        and attribute_value = 'J Limited' 
        then 1 
       end) > 0 
    ) a on s.student_id = a.student_id; 
+0

@Downvoter - コメントを残してください。 – GurV

+0

スクリプトは私にとって完璧に機能しました。ありがとうございました! – ChrisZ

0

は、あなたが気に属性:

select * from student s 
join student_attribute school on school.student_id = s.student_id 
join student_attribute company on company.student_id = s.student_id 
where company.attribute_value='J Limited' 
and school.attribute_value='UofJ' 
関連する問題