AWS Redshift 查询多个模式的

AWS Redshift query multiple schema's

是否可以在我的 Redshift 数据库中查询多个模式并合并结果?

像这样:

SELECT DISTINCT name, SUM(usage) AS totalUsage
FROM schemaOne.terms, schemaTwo.terms

会抛出错误:

Amazon Invalid operation: column reference "name" is ambiguous;

那么,这可能吗?这是一个好的做法吗?我想为每个客户创建一个模式,它将有自己的条款(标签)table 和其他 tables.

例如

SchemaOne:条款

id,  name,  description,  usage
_______________________________
1    css    CSS is bla.   14
2    html   HTML rocks!   9

SchemaTwo:条款

id,  name,  description,  usage
_______________________________
1    css    CSS is cool.  8
2    other  x             4

现在我想合并结果,可以输出如下内容:

name   totalUsage
_________________
css    22
html   9
other  4

首先在派生的table中做UNION ALL,然后应用GROUP BY:

select name, sum(usage) as totalUsage
from
(
    select name, usage
    from SchemaOne.terms
    union all
    select name, usage
    from SchemaTwo.terms
) dt
group by name

请注意,某些产品有nameusage作为保留字,因此您可能需要将它们分隔为"name" and/or "usage"

也许性能更好的版本:

select name, sum(usage) as totalUsage
from
(
    select name, sum(usage) as usage
    from SchemaOne.terms
    group by name
    union all
    select name, sum(usage) as usage
    from SchemaTwo.terms
    group by name
) dt
group by name

原回答:

如果相同的列名存在于多个 table 中,您必须限定该列,即将 table 名称放在列名之前:

SELECT DISTINCT schemaOne.terms.name, SUM(usage) as totalUsage
FROM schemaOne.terms, schemaTwo.terms

Table 别名很方便:

SELECT DISTINCT s1t.name, SUM(usage) as totalUsage
FROM schemaOne.terms s1t, schemaTwo.terms s2t