繁体   English   中英

SQL表名称作为变量

[英]SQL table names as variable

有没有更好的方法来编写以下SQL:

select item, price, 'Global Sales' as source_table from global_sales
union all
select item, price, 'Regional Sales' as source_table from regional_sales
union all
select item, price, 'Local Sales' as source_table from local_sales

我有20多个表要合并,但想知道是否有更有效的方法来编写此sql。 最后,我想使用SQL作为视图。

这种查询表明表设计不良。

在短期内,您可以编写一个小程序为您做重复的工作。 这是Ruby中的示例。

#!/usr/bin/env ruby

tables = [
  'global_sales',
  'regional_sales',
  'local_sales'
]

def table2column(table)
  return table.split('_')
    .map { |word| word[0].upcase!; word }
    .join(" ")
end

puts tables.map { |table|
  column = table2column(table)
  "select item, price, '#{column}' from #{table}\n"
}.join("union all\n")

假设我们根据销售地点的不同而对所有销售进行了分类。

您的表设计可以改进。 如果其余所有数据都相等,则所有销售额都可以存储在单个表格中,且表格的位置尽可能狭窄。

create table sales (
    id integer primary key,
    item integer references items(id),
    price numeric(10,2) not null,
    location integer references locations(id)
);

create table locations (
     id integer primary key,
     name text,
     ... etc ...
);

还有一张表格,用于指定每个位置所在的区域。

create table regions (
     id integer primary key,
     name text,
     ... etc ...
);

create table regional_locations (
     id integer primary key,
     location integer references locations(id),
     region integer references regions(id)
);

然后获得全球销售很容易。

select item, price from sales;

可以实现一个地区的销售。

select item, price, r.name, l.name
from sales s
-- Get the region for each location
join regional_locations rl on rl.location = s.location
 -- Get the region name
 and regions r on rl.region = r.id
 -- Get the location name
 and locations l on s.location = l.id
where rl.region = ?

为了向后兼容,每个旧表都成为一个视图。 例如...

create view global_sales
    select id, item, price from sales;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM