java - 动态属性名称搜索

标签 java sql oracle jpa

假设我有一个像这样的学生表:

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/

相关文章:

sql - 在 Postgres 中查找用于聚合的元组的通用方法?

sql - 检索分层组...无限递归

sql - 将 guids 转换为数值

sql - 当另一个字段已经在 GROUP BY 中时,WHERE 大于计数的 SQL 查询

java - 我的最大乘积算法有什么问题

java - 将帧(android 中的 mat 数据)从 android 传递到 native c++ 并检测人脸

java - 如何使用 Joda 将服务器时间转换为本地时间?

sql - Entity Framework - 如何过滤预先加载的导航/关系属性?

SQL group by "date"问题

java - 从坐标创建椭圆曲线点对象