SQL表名称作为变量

时间:2018-09-05 22:07:05

标签: sql oracle

是否有更好的方法编写以下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作为视图。

1 个答案:

答案 0 :(得分:1)

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

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

Vector<T>
  

让我们假设由于要出售的商品因位置而异,我们对所有销售都进行了分类。

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

#!/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 = ?