2012-04-22 42 views
0

我有两个表,他们有相同的ID名称(我不能改变表的设计方式),我试图查询table2的ID,我怎么会这样做,当他们是加入?同名Postgresql调用列

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; 

回答

0

它使用select *你不能选择。 试试这个:如果你希望两个“身份证”

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

别名列小号

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

对于其他任何事情,SELECT *通常都是个坏主意;如果您使用它,基于模式更改,事情可能会以不可预知和令人惊讶的方式突破。 – kgrittn 2012-04-22 15:55:44

0

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

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