获取具有仅属于特定类别列表的关联的结果
Getting results with association that belongs only to a certain list of categories
我有两张这样的小桌子:
用户:
+----+-------+
| 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 拥有图像和声音类型的资源
史密斯拥有声音类型的资源
库尔特拥有文字和图像
Tim 只拥有声音
问题是:我想检索只拥有文本 and/or 图片的用户,如果用户拥有除文本或图片之外的任何其他类型的资源,则不应在结果集。
有什么方法可以用标准或 HQL 来实现吗?
目前,我的查询返回的是拥有文本或图像的用户,但他们也拥有其他类型的资源:
+----+-------+
| id | name |
+----+-------+
| 1 | John |
| 2 | Mike |
| 4 | Kurt |
| 5 | Tim |
+----+-------+
结果集应该只显示 John 和 Kurt,因为只有他们拥有文本 and/or 图片。
假设您的用户域 class 类似于
class User {
String name
}
资源 class 看起来像
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'
)""")
我有两张这样的小桌子:
用户:
+----+-------+
| 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 拥有图像和声音类型的资源 史密斯拥有声音类型的资源 库尔特拥有文字和图像 Tim 只拥有声音
问题是:我想检索只拥有文本 and/or 图片的用户,如果用户拥有除文本或图片之外的任何其他类型的资源,则不应在结果集。
有什么方法可以用标准或 HQL 来实现吗?
目前,我的查询返回的是拥有文本或图像的用户,但他们也拥有其他类型的资源:
+----+-------+
| id | name |
+----+-------+
| 1 | John |
| 2 | Mike |
| 4 | Kurt |
| 5 | Tim |
+----+-------+
结果集应该只显示 John 和 Kurt,因为只有他们拥有文本 and/or 图片。
假设您的用户域 class 类似于
class User {
String name
}
资源 class 看起来像
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'
)""")