2017-04-03 142 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'學生名單。易:

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

然而,我的現實是過去的2個屬性存儲在學生表作爲列,但在一個單獨的表稱爲student_attribute爲行:

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 

我的任務是找到列表來自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 

然後,你可以加入它與學生表來獲得相應的細節。

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'