2

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;

3 Answers 3

7

Alias the columns if you want both "id"s

SELECT table1.id AS id1, table2.id AS id2
FROM table1...
Sign up to request clarification or add additional context in comments.

1 Comment

SELECT * is generally a bad idea anyway for anything other than ad hoc queries; if you use it things can break in unpredictable and surprising ways based on schema changes.
3

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 ...

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.