PostgreSQL-选择具有某些标签的项目,但在结果中保留所有标签

发布于 2025-01-20 11:11:30 字数 959 浏览 2 评论 0原文

我的标签搜索有问题,数据库正确返回包含标签的图像,但所有其他标签都被删除。我将所有标签存储在单独的表“标签映射”中。

这是我搜索“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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

坏尐絯 2025-01-27 11:11:30

答案是将其分组为子查询并在其后使用 WHERE。我更改了表结构,因此查询与 OP 中的查询有点不同。

SELECT * FROM (
  SELECT posts.*, json_agg(DISTINCT images.*) AS images, array_agg(DISTINCT "tag map".tag) AS tags
  FROM posts
  JOIN images ON posts."postID" = images."postID"
  JOIN "tag map" ON posts."postID" = "tag map"."postID"
  GROUP BY posts."postID"
) AS posts
WHERE tags @> $1

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.

SELECT * FROM (
  SELECT posts.*, json_agg(DISTINCT images.*) AS images, array_agg(DISTINCT "tag map".tag) AS tags
  FROM posts
  JOIN images ON posts."postID" = images."postID"
  JOIN "tag map" ON posts."postID" = "tag map"."postID"
  GROUP BY posts."postID"
) AS posts
WHERE tags @> $1
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文