【问题标题】:postgresql calling column with same namepostgresql 调用具有相同名称的列
【发布时间】:2012-04-22 03:48:36
【问题描述】:

我有两个表,它们具有相同的 ID 名称(我无法更改表的设计方式)并且我正在尝试查询 table2 的 ID,当它们连接时我将如何执行此操作?

create table table1(
    id          integer, -- PG: serial
    description MediumString not null,
    primary key (id)
);


create table table2 (
    id          integer, -- PG: serial
    tid         references table1(id),
    primary key (id)
);

所以基本上当它们加入时,如果我执行以下查询,两列将具有相同的名称“id”

select * from table1
join table2 on table1.id = table2.tid;

【问题讨论】:

    标签: postgresql


    【解决方案1】:

    如果您想要两个“id”,则为列命名

    SELECT table1.id AS id1, table2.id AS id2
    FROM table1...
    

    【讨论】:

    • SELECT * 对于临时查询以外的任何事情通常都是个坏主意;如果您使用它,事情可能会根据架构更改以不可预测和令人惊讶的方式中断。
    【解决方案2】:

    如果您想查询两个表上的所有 * 但仍然能够引用特定的 id,您也可以这样做,您最终会得到可能不会使用的重复 id 列,但在某些情况下,如果您真的需要所有的数据,值得。

    select table1.*, table2.*, table1.id as 'table1.id', table2.id as 'table2.id'
    from ...
    

    【讨论】:

      【解决方案3】:

      您无法使用select * 选择它。 试试这个:

      select table1.id, table1.description, table2.id, table2.tid
      from table1
      inner join table2
       on table1.id = table2.tid
      

      【讨论】:

        猜你喜欢
        • 2020-10-15
        • 2014-07-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-15
        • 2011-11-20
        • 1970-01-01
        相关资源
        最近更新 更多