批量创建别名?

时间:2016-01-21 17:26:00

标签: postgresql

我正在尝试加入三个表格productstaxes& categories。所有这些表都有冲突的列名。我知道我们通过创建别名来解决这个冲突。

products:
    id
    name
    ...

taxes
    id
    name
    ...

categories
    id
    name
    ...

我的问题是,是否有一种方便的方法来批量创建别名?我的意思是像

SELECT products.* as product.*, taxes.* as tax.*, categories.* as category.*
...

我希望结果集包含以下列:

product.id, product.name, tax.id, tax.name, ...

或者,我是否必须坚持使用繁琐的东西:

SELECT products.id as product_id, products.name as product_name,
       taxes.id as tax_id, taxes.name as tax_name, ...

1 个答案:

答案 0 :(得分:0)

您在类固醇上搜索*。不幸的是,SQL中没有这样的功能。

解决方法1:

在您喜欢的文本编辑器(vim,atom,...)中使用块选择功能。将每列放在新行中。阻止选择以写入AS和表前缀。然后阻止选择和复制列名称。

解决方法2:

使用INFORMATION_SCHEMA.COLUMNS生成选择列表:

SELECT 
 string_agg(FORMAT('%s.%s AS %s_%s', "table_name",
                   column_name,"table_name", column_name), ', ')
FROM information_schema.columns
WHERE "table_name" IN ('products', 'taxes', 'categories');

SqlFiddleDemo

您可以使用E',\n'将每列放在新行中。

输出:

╔════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╗
║                                                                                   string_agg                                                                                   ║
╠════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╣
║ products.id AS products_id, products.name AS products_name, taxes.id AS taxes_id, taxes.name AS taxes_name, categories.id AS categories_id, categories.name AS categories_name ║
╚════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╝