假设我有一个像这样的学生表:
student_id name address ... school employer
1 Chris 2 John UofJ J Limited
2 Ann 3 Doe UofD D limited
现在我需要查找拥有学校 = 'UofJ'
和雇主 = '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方式的解决方案。
最佳答案
您可以使用条件聚合来找出哪个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;
关于java - 动态属性名称搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43190874/