我有两张这样的小 table :
用户:
+----+-------+
| 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 |
+----+------------+-------+---------+
鉴于此,我们可以看到
约翰拥有文本和图像类型的资源
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'
)""")
关于grails - 获取仅属于特定类别列表的关联结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29242670/