让我们说我有一个User
的Moder Posts
。
所以现在例如我选择男性用户:
SELECT "users".* FROM "users" WHERE (gender = 'male')
如何扩展我的搜索查询并仅选择拥有带标记[sport,holiday]
的帖子的男性用户?
如果我只需要使用Posts
,我只需致电:
SELECT "posts".* FROM "posts" WHERE "posts"."tag" IN ('sport','holiday')
所以我尝试的是:
SELECT "users".* FROM "users" INNER JOIN "posts" ON "posts"."user_id" = "users"."id"
WHERE "posts"."tag" IN ('sport', 'holiday') AND gender = 'male'
此搜索查询的问题在于,如果他有更多带有标签['sport','holiday']的帖子,则会多次返回相同的用户。我如何更改我的搜索查询,以便它只返回一次用户?感谢
答案 0 :(得分:2)
尝试GROUP BY
GROUP BY users.id
或DISTINCT
答案 1 :(得分:1)
SELECT DISTINCT "users".* FROM "users" INNER JOIN "posts" ON "posts"."user_id" = "users"."id"
WHERE "posts"."tag" IN ('sport', 'holiday') AND gender = 'male'
将返回唯一的行
或正如第一条评论所说,使用
组SELECT "users".* FROM "users" INNER JOIN "posts" ON "posts"."user_id" = "users"."id"
WHERE "posts"."tag" IN ('sport', 'holiday') AND gender = 'male'
Group by users.id
答案 2 :(得分:1)
您可以将IN运算符与子查询一起使用
SELECT "users".*
FROM "users"
WHERE "users"."id" IN (
SELECT "posts"."user_id"
FROM "posts"
WHERE "posts"."tag" IN ('sport', 'holiday')
) AND gender = 'male'
或ANY
SELECT "users".*
FROM "users"
WHERE "users"."id" = ANY(
(
SELECT ARRAY(
SELECT "posts"."user_id"
FROM "posts"
WHERE "posts"."tag" IN ('sport', 'holiday'))
)::integer[]
) AND gender = 'male'