正在获取只属于某个类别列表的关联结果



我有两个类似的小表:

用户:

+----+-------+
| id | name  |
+----+-------+
|  1 | John  |
|  2 | Mike  |
|  3 | Smith |
|  4 | Kurt  |
|  5 | Tim   |
+----+-------+

资源:

+----+------------+-------+---------+
| id |    name    | type  | user_id |
+----+------------+-------+---------+
|  1 | sunset     | text  |       1 |
|  2 | sunrise    | image |       2 |
|  3 | moon       | image |       1 |
|  4 | earth      | sound |       3 |
|  5 | clouds     | sound |       2 |
|  6 | tree       | image |       4 |
|  7 | flower     | text  |       4 |
|  8 | water      | text  |       4 |
|  9 | wind       | text  |       1 |
| 10 | animal     | image |       1 |
| 11 | open_door  | sound |       5 |
| 12 | close_door | sound |       5 |
+----+------------+-------+---------+

鉴于此,我们可以看到

John拥有文本和图像类型的资源Mike拥有图像和声音类型的资源史密斯拥有类型声音的资源Kurt拥有文本和图像蒂姆只拥有声音

问题是:我想检索只拥有文本和/或图像的用户,如果用户拥有任何其他类型的非文本或图像资源,则不应在结果集中提取该用户。

有什么方法可以通过标准或HQL来实现这一点吗?

目前,我的查询返回的是拥有文本或图像的用户,但他们也拥有其他类型的资源:

+----+-------+
| id | name  |
+----+-------+
|  1 | John  |
|  2 | Mike  |
|  4 | Kurt  |
|  5 | Tim   |
+----+-------+

结果集应该只显示John和Kurt,因为他们是唯一拥有文本和/或图像的人。

假设您的用户域类看起来像

class User {
   String name
}

资源类看起来有点像

class Resource {
   String name
   String type
   User user
}

然后你可以使用这个HQL:

User.executeQuery("""
   select distinct r.user from Resource r
   where (r.type='image' or r.type='text')
     and r.user not in (
         select distinct r.user from Resource r where r.type<>'image' and r.type<>'text'
     )""")

最新更新