简体   繁体   English

AWS Redshift查询多个架构

[英]AWS Redshift query multiple schema's

Is it possible to query multiple schema's within my Redshift database and combine the results? 是否可以在我的Redshift数据库中查询多个架构并合并结果?

Something like this: 像这样:

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

will throw an error: 会抛出一个错误:

Amazon Invalid operation: column reference "name" is ambiguous; Amazon无效操作:列引用“名称”不明确;

So, is this possible and would this be a good practice? 那么,这可能吗,这将是一个好习惯吗? I would like to create a schema for each client which will have it's own terms (tags) table and other tables. 我想为每个客户端创建一个架构,该架构将具有自己的条件(标签)表和其他表。

For example 例如

SchemaOne: terms SchemaOne:条款

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

SchemaTwo: terms 模式二:术语

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

Now I would like to combine the results, which could output something like: 现在,我想合并结果,它可以输出如下内容:

name   totalUsage
_________________
css    22
html   9
other  4

First do UNION ALL in a derived table, then apply GROUP BY : 首先在派生表中执行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

Note that some products have name and usage as reserved words, so you may need to delimit them as "name" and/or "usage" . 请注意,某些产品使用nameusage作为保留字,因此您可能需要将它们分隔为"name"和/或"usage"

Perhaps better performance version: 也许是性能更好的版本:

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

Original answer : 原始答案

If the same column name exists in more than one table, you have to qualify that column, ie put the table name before the column name: 如果多个表中存在相同的列名,则必须限定该列,即,将表名放在该列名之前:

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

Table aliases are convenient: 表别名很方便:

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

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

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