0

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

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

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

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

4

1 回答 1

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'

但同样:修复你的数据模型。这会越来越伤害你

于 2013-01-09T16:57:56.493 回答