查询多个具有复杂关系的表

2024-03-20

我想要的查询超出了我的 SQL 知识,所以我希望在这里得到一些帮助。我想在 postgreSQL 9.2 中将多个表的关系合并为一个表。我知道程序,但不知道SQL。

此查询将包含 4 个表:

  • 愿望清单:与一个或多个列表相关联并且具有首选商店
  • 愿望清单:保存列表和愿望清单之间的关系
  • item:与列表关联并具有首选商店
  • 首选商店:这保存了商店和首选商店之间的关系(每个首选商店都是一个单独的行 首选商店。因此,如果一项或愿望清单有多个 首选商店,prefered_store.id 对于这些行将是相同的)

The tables look like this (with irrelevant columns removed): enter image description here

And here is what the resulting table would look like: enter image description here

让我解释一下结果表:

  • item_id:就是这样,项目的 id
  • 商品商店评论:存储/评论 与此项目关联的所有 Preferred_stores 行中的对(存储/注释以逗号分隔,对以分号分隔)
  • 愿望清单商店:关联的愿望清单的 Preferred_stored 的存储 ID 包含该项目所在的列表(以逗号分隔)

我已经用上面示例表的实际结果填充了 item_info 表,所以我想它应该很清楚,但如果您没有得到任何结果,请告诉我。

我按照评论中的建议创建了一个 SQLFiddle:http://sqlfiddle.com/#!12/9fd60 http://sqlfiddle.com/#!12/9fd60它包含与图像中相同的架构和值。


这应该做你想要的:

WITH a AS (
  SELECT item.id, string_agg(prefered_store.store::varchar, ',') wishlist_stores
  FROM item, list_wishlist, wishlist, prefered_store
  WHERE item.list=list_wishlist.list
    AND list_wishlist.wishlist=wishlist.id
    AND wishlist.prefered_stores=prefered_store.id
  GROUP BY item.id
), b AS (
  SELECT item.id, 
    string_agg(
      prefered_store.store::varchar || ',' || prefered_store.comment,
      ' ; ') item_stores_comments
    FROM item, prefered_store
    WHERE item.prefered_stores=prefered_store.id
    GROUP BY item.id
)
SELECT a.id,item_stores_comments,wishlist_stores 
FROM a,b
WHERE a.id=b.id
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

查询多个具有复杂关系的表 的相关文章

随机推荐