简体   繁体   English

获取表别名以显示为查询结果中列名的一部分

[英]Get table alias names to appear as part of the column names in query results

In Postgres, a query like this: 在Postgres中,查询如下:

SELECT a.id, b.id FROM table1 a INNER JOIN table2 b on a.id=b.id;

Will return 'deconflicted' column names like: 将返回“去冲突的”列名称,例如:

a.id, b.id a.id,b.id

However, in Oracle, the id columns just keep their original names: 但是,在Oracle中, id列仅保留其原始名称:

id, id id,id

My problem here is that my follow-on tools are confused by the duplicate column names. 我的问题是重复的列名使我的后续工具感到困惑。

In this example, I've only listed 2 columns, but in reality there are 100's, and I'd prefer to not have to list them all out. 在此示例中,我仅列出了2列,但实际上有100列,我希望不必将它们全部列出。

Is there a way to do this without having to specify all of the column names (there are 100's). 有没有一种方法可以不必指定所有列名(有100个)。

Try this: 尝试这个:

SELECT a.id as 'table1 a', b.id as 'table2 b' FROM table1 a INNER JOIN table2 b on a.id=b.id group by a.id, b.id;

You can name your results with as followed by the name. 您可以命名您的结果as后面的名字。 If you want to use JOIN , you have to use GROUP BY followed by your selected items if you don't want duplicate values. 如果要使用JOIN ,如果不想重复值,则必须使用GROUP BY然后再使用所选的项目。

You can solve the particular problem with id by fixing the join : 您可以通过修复join解决id的特定问题:

SELECT *
FROM table1 a INNER JOIN
     table2 b 
     USING (id);

If id is the only duplicate column, then this may solve your problem. 如果id是唯一重复的列,则可以解决您的问题。

I suspect there won't be because table names (or aliases) aren't a requirement. 我怀疑那不是因为不需要表名(或别名)。 For example the following is valid SQL for Oracle, but there's no viable prefix to include in column naming. 例如,以下是适用于Oracle的有效SQL,但是在列命名中没有可行的前缀。

SELECT * FROM 
   (select 1 a, 2 b from dual) 
  join 
   (select 1 a, 3 b from dual) 
  using (a)

But I think Postgres requires those FROM subqueries to be aliased 但是我认为Postgres要求对FROM子查询使用别名

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

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