gpt4 book ai didi

postgresql - PostgreSQL 中的动态表名

转载 作者:行者123 更新时间:2023-11-29 14:23:12 25 4
gpt4 key购买 nike

我的情况是多个表包含基于国家/地区的相似信息。更改数据库模式不是一种选择,我对使用存储过程不感兴趣。与对每个国家/地区执行一个查询相比,我更愿意在返回多行的单个查询中获取所有内容。

首先,我有一个定义表,其中列出了我们有表的所有国家/地区:

countries
+============+========+
| country_id | prefix |
+============+========+
| 1 | us |
+------------+--------+
| 2 | ca |
+------------+--------+

其次,我有一个关系表:

relationships
+========+============+==============+
| rel_id | country_id | upc |
+========+============+==============+
| 1 | 1 | 111111111111 |
+--------+------------+--------------+
| 2 | 2 | 111111111111 |
+--------+------------+--------------+
| 3 | 1 | 222222222222 |
+--------+------------+--------------+
| 4 | 2 | 222222222222 |
+--------+------------+--------------+
| 5 | 2 | 333333333333 |
+--------+------------+--------------+
| 6 | 1 | 444444444444 |
+--------+------------+--------------+

然后,我有两个名为“us_products”和“ca_products”的表。如果 countries 表中存在条目,则存在名为 [countries.prefix]_products 的表。所有 *_products 表彼此相同。相同的列和相同的数据类型。

us_products
+============+==============+=======+
| product_id | upc | title |
+============+==============+=======+
| 1 | 111111111111 | Shoe! |
+------------+--------------+=======+
| 2 | 222222222222 | Tie |
+------------+--------------+=======+
| 3 | 444444444444 | Sock |
+------------+--------------+=======+

ca_products
+============+==============+=======+
| product_id | upc | title |
+============+==============+=======+
| 1 | 111111111111 | Shoe. |
+------------+--------------+=======+
| 2 | 222222222222 | Tie |
+------------+--------------+=======+
| 3 | 333333333333 | Shirt |
+------------+--------------+=======+

目标是使查询格式类似于以下内容(显然这是行不通的,否则我不会问这个问题...):

SELECT
countries.prefix,
products.title
FROM
relationships
INNER JOIN
[countries.prefix]_products AS products
ON
relationships.upc = products.upc
WHERE
relationships.upc = '111111111111'

应该返回:

+========+=======+
| prefix | title |
+========+=======+
| us | Shoe! |
+--------+-------+
| ca | Shoe. |
+--------+-------+

感谢您的帮助!如果这样做的唯一方法是通过存储过程,那么我想我没有任何其他选择,在这种情况下,您是否介意将一个示例过程和查询放在一起,以对上述表结构执行?

最佳答案

如果不想创建 View ,可以使用公用表表达式作为“临时” View :

with normalized_products as (
select 1 as country_id,
product_id,
upc,
title
from us_products
union all
select 2 as country_id,
product_id,
upc,
title
from ca_products
)
SELECT countries.prefix,
products.title
FROM relationships as rel
JOIN normalized_products as prod
ON rel.upc = prod.upc
and rel.country_id = prod.country_id
where rel.upc = '111111111111'

但再次强调:一定要修复你的数据模型。这会越来越伤害你

关于postgresql - PostgreSQL 中的动态表名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14242215/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com