PostgreSQL-选择具有某些标签的项目,但在结果中保留所有标签
我的标签搜索有问题,数据库正确返回包含标签的图像,但所有其他标签都被删除。我将所有标签存储在单独的表“标签映射”中。
这是我搜索“tag1”的结果(图像实际上具有比 tag1 更多的标签):
[{"postID": 1, "images": {"imageID": 1, "tags": ["tag1"]}}]
这是我想要搜索“tag1”的结果:
[{"postID": 1, "images": {"imageID": 1, "tags": ["tag1", "tag2", "tag3"]}}]
这是生成第一个结果的查询:
WITH image_tags AS (
SELECT images."post id", json_build_object (
'imageID', images."image id",
'tags', json_agg("tag map".tag)
) AS image,
FROM images
JOIN "tag map" ON images."image id" = "tag map"."image id"
WHERE "tag map".tag = ALL ($1)
GROUP BY images."post id", images."image id"
)
SELECT posts."post id" AS "postID", json_agg(image_tags.image) AS images
FROM posts
JOIN image_tags ON posts."post id" = image_tags."post id"
GROUP BY posts."post id"
I have a problem with my tag search where the database correctly returns the images containing the tags, BUT all of the other tags are stripped. I store all of the tags in a separate table "tag map".
This is my result for search "tag1" (image actually has more tags than just tag1):
[{"postID": 1, "images": {"imageID": 1, "tags": ["tag1"]}}]
This is the result that I want for search "tag1":
[{"postID": 1, "images": {"imageID": 1, "tags": ["tag1", "tag2", "tag3"]}}]
This is the query that generates the first result:
WITH image_tags AS (
SELECT images."post id", json_build_object (
'imageID', images."image id",
'tags', json_agg("tag map".tag)
) AS image,
FROM images
JOIN "tag map" ON images."image id" = "tag map"."image id"
WHERE "tag map".tag = ALL ($1)
GROUP BY images."post id", images."image id"
)
SELECT posts."post id" AS "postID", json_agg(image_tags.image) AS images
FROM posts
JOIN image_tags ON posts."post id" = image_tags."post id"
GROUP BY posts."post id"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
答案是将其分组为子查询并在其后使用 WHERE。我更改了表结构,因此查询与 OP 中的查询有点不同。
The answer is group it into a subquery and use WHERE after. I changed my table structure so the query is a bit different than in OP.