所以我想选择所有表,其中另一个表中的行子集与给定值匹配。 我有以下表格:
Main Profile:
+----+--------+---------------+---------+
| id | name | subprofile_id | version |
+----+--------+---------------+---------+
| 1 | Main 1 | 4 | 1 |
| 2 | Main 1 | 5 | 2 |
| 3 | Main 2 | ... | 1 |
+----+--------+---------------+---------+
Sub Profile:
+---------------+----------+
| subprofile_id | block_id |
+---------------+----------+
| 4 | 6 |
| 4 | 7 |
| 5 | 8 |
| 5 | 9 |
+---------------+----------+
Block:
+----------+-------------+
| block_id | property_id |
+----------+-------------+
| 7 | 10 |
| 7 | 11 |
| 7 | 12 |
| 7 | 13 |
| 8 | 14 |
| 8 | 15 |
| 8 | 16 |
| 8 | 17 |
| ... | ... |
+----------+-------------+
Property:
+----+--------------------+--------------------------+
| id | name | value |
+----+--------------------+--------------------------+
| 10 | Description | XY |
| 11 | Responsible person | Mr. Smith |
| 12 | ... | ... |
| 13 | ... | ... |
| 14 | Description | XY |
| 15 | Responsible person | Mrs. Brown |
| 16 | ... | ... |
| 17 | ... | ... |
+----+--------------------+--------------------------+
用户可以在属性表上定义多个条件。例如:
我需要所有具有最高匹配属性的,具有最高版本的“主要配置文件”,当然还有更多不匹配的属性。 它应该在JPA中可行,因为我会将其转换为QueryDSL以使用用户输入来构建类型安全的动态查询。
我已经搜索了所有与类似问题有关的问题,但无法将答案投射到我的问题上。 另外,我已经尝试编写一个运行良好的查询,但是使用至少一个匹配条件检索了所有行。因此,我需要集合中的所有属性,但只获取匹配的属性(获取连接,在我的代码示例中缺少)。
from MainProfile as mainProfile
left join mainProfile.subProfile as subProfile
left join subProfile.blocks as block
left join block.properties as property
where mainProfile.version = (select max(mainProfile2.version)from MainProfile as mainProfile2 where mainProfile2.name = mainProfile.name) and ((property.name = 'Description' and property.value = 'XY') or (property.name = 'Responsible person' and property.value = 'Mr. Smith'))
运行查询,我得到两行:
由于“主要2人”中“负责人”的不匹配,我本来只希望获得一排
所以我找到了一个可行但可以改进的解决方案:
select distinct mainProfile
from MainProfile as mainProfile
left join mainProfile.subProfile as subProfile
left join subProfile.blocks as block
left join block.properties as property
where mainProfile.version = (select max(mainProfile2.version)from MainProfile mainProfile2 where mainProfile2.name = mainProfile.name)
and ((property.name = 'Description' and property.content = 'XY') or (property.name = 'Responsible person' and property.content = 'Mr. Smith'))
group by mainProfile.id
having count (distinct property) = 2
它实际上检索正确的“主要配置文件”。但是问题是,只有两个找到的属性被获取。我需要所有属性,但由于需要进一步处理。