简体   繁体   中英

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.

A child has (among others) the following attributes:

  • User
  • Type

I now want to find all parent elements, who have at least both the following children:

  • First child with user = 'user1' and type = 'type1' AND
  • Second child with user = 'user2' and type == 'type2' OR
  • First child with user = 'user1' and type = 'type2' AND
  • Second child with user = 'user2' and type = 'type1'

Eg an entity could have 10 children, but two of them must match the above criteria.

Do you have any hints how to approach it with SQL/JPA Criteria API?

Is the EXISTS clause the way to go, something like this:

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 columns are the join columns for the 1:n relation.

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.

Example input: 'user1', 'user2' Result: Mail 1 and 3, but not Mail 4, because in Mail 4 both users are only receivers.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM