动态属性名称搜索

时间:2017-04-03 17:32:41

标签: java sql oracle jpa

考虑我有这样的学生表:

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表中,但在名为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_attributeschool = 'UofJ'查找此employer = 'J Limited'表格中的学生ID列表。我该怎么办?

此外,我使用Springboot JPS存储库来进行查询,所以我愿意以sql方式或JPA方式听取解决方案。

2 个答案:

答案 0 :(得分:1)

您可以使用条件聚合来找出哪个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;

答案 1 :(得分: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'