SNpn
SNpn

Reputation: 2207

postgresql calling column with same name

I have two tables, where they have the same ID name (I cannot change the way the tables are designed) and I'm trying to query table2's ID, how would I do this when they are joined?

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)
);

So basically when they're joined, two columns will have the same name "id" if I do the following query

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

Upvotes: 2

Views: 7630

Answers (3)

Eric
Eric

Reputation: 514

If you want to query all * on both tables but still be able to reference a specific id you can do that too, you will end up with duplicate id columns that you probably won't use, but in some situations if you really need all the data, it's worth it.

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

Upvotes: 3

Richard Huxton
Richard Huxton

Reputation: 22952

Alias the columns if you want both "id"s

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

Upvotes: 7

t_motooka
t_motooka

Reputation: 565

You cannot select it using select *. try this :

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

Upvotes: 0

Related Questions