Aidan Ewen
Aidan Ewen

Reputation: 13308

Exclude foreign keys from sql query

I've got some sql joining a few tables together

SELECT contact.contact_id,
        form1.*,
        form2.*
FROM contact
INNER JOIN form1
ON contact.contact_id = form1.contact_id
INNER JOIN form2
ON contact_contact_id = form2.contact_id

I want to avoid repeating the 'contact_id' column in my output without having to write every field name in the table (ie I want to keep using form1.* and form2.* as this will make the report much easier to maintain - fields are liable to change). Is this possible? I'm using Postgres.

Upvotes: 0

Views: 698

Answers (2)

Burleigh Bear
Burleigh Bear

Reputation: 3314

If contact_id is the only column name that the tables share, you can use 'natural join' to join the tables and you will end up with only one copy of the joining column.

Upvotes: 1

Madhivanan
Madhivanan

Reputation: 13700

Only way is "Dont use *". You need to explicitely type out the required column. This is a good practice when you use JOINs. If the columns are too many, make use of the result

select column_name from information_schema.columns
where table_name='your table' and column_name<>'contact_id'

Upvotes: 1

Related Questions