[英]SQL query with 1:n relation, find all entities which have two matching children matching
I have a simple parent-child relation (1:n, @OneToMany), mapped by JPA. 我有一个简单的父子关系(1:n,@ OneToMany),由JPA映射。
A child has (among others) the following attributes: 一个孩子(除其他外)具有以下属性:
I now want to find all parent elements, who have at least both the following children: 我现在要查找所有父元素,它们至少具有以下两个子元素:
Eg an entity could have 10 children, but two of them must match the above criteria. 例如,一个实体可以有10个孩子,但是其中两个必须符合上述条件。
Do you have any hints how to approach it with SQL/JPA Criteria API? 您是否有任何使用SQL / JPA Criteria API进行处理的提示?
Is the EXISTS clause the way to go, something like this: 是EXISTS子句走的路,是这样的:
SELECT * FROM Parent parent
WHERE EXISTS (SELECT child FROM Child WHERE (child.user = 'user1' AND child.type = 'type1' OR ...) AND child.id=parent.id)
OR
EXISTS (SELECT child FROM Child WHERE (child.user = 'user1' AND child.type = 'type2' OR ...) AND child.id=parent.id)
Thanks for your help! 谢谢你的帮助!
UPDATE: The parent represents a "mail", the child relations represent the sender and receivers of the mail, like this: 更新:父级代表“邮件”,子级关系代表邮件的发送者和接收者,如下所示:
Parent Table (Mail):
|id | subject |
|1 | Hello World |
|2 | Foo Bar |
|3 | Example |
|4 | Test |
Child Table:
|id | user | type |
|1 | user1@mail| SENDER |
|1 | user2@mail| RECEIVER |
|1 | user3@mail| RECEIVER |
|2 | user1@mail| SENDER |
|2 | user4@mail| RECEIVER |
|2 | user5@mail| RECEIVER |
|3 | user2@mail| SENDER |
|3 | user1@mail| RECEIVER |
|3 | user5@mail| RECEIVER |
|4 | user3@mail| SENDER |
|4 | user1@mail| RECEIVER |
|4 | user2@mail| RECEIVER |
Primary key of the child table is a composite key of (id,user,type). 子表的主键是(id,user,type)的组合键。 id columns are the join columns for the 1:n relation. id列是1:n关系的连接列。
I want to find all mails, which are either sent by user1 and received by user2 or vice versa, eg mails which were exchanged between two users. 我想查找所有由user1发送并由user2接收的邮件,反之亦然,例如,两个用户之间交换的邮件。
Example input: 'user1', 'user2' Result: Mail 1 and 3, but not Mail 4, because in Mail 4 both users are only receivers. 输入示例:'user1','user2'结果:邮件1和3,但不包含邮件4,因为在邮件4中,两个用户都是接收者。
One neat trick is to count the number of unique children such a parent has: 一个巧妙的技巧是计算这样的父母拥有的唯一孩子的数量:
SELECT *
FROM parent p
WHERE EXISTS (SELECT child_id
FROM child c
WHERE user IN ('user1', 'user2') AND
type IN ('type1', 'type2') AND
c.parent_id = p.id
GROUP BY child_id
HAVING COUNT(DISTINCT user) = 2 AND
COUNT(DISTINCT type) = 2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.