PostgreSQL中的动态表名

时间:2013-01-09 16:50:47

标签: postgresql postgresql-9.2

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

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

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. |
+--------+-------+

感谢您的帮助!如果通过存储过程执行此操作的唯一方法,那么我认为我没有任何其他选项,在这种情况下,您是否介意将上述表结构中执行的示例过程和查询放在一起?

1 个答案:

答案 0 :(得分:3)

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

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'

但是又一次:修复你的数据模型。这会越来越伤害你