Cosmin_Victor
Cosmin_Victor

Reputation: 154

Postgres SQL SELECT data from the table the entry exists with ID

I have the following scenario.I have 3 tables with the following structure.

TABLE A
 -entry_id (PRIMARY KEY, INTEGER)

TABLE B 
 -entry_id (FOREIGN_KEY -> TABLE A)
 -content (TEXT)

TABLE C
  -entry_id (FOREIGN_KEY -> TABLE A)
  -content (INTEGER)

I want to retrive the content cell value from either table B or table C. The value can be in just one of the table. So it is either table B or C witch have an entry with a given entry_id.

PS. Sorry if duplicate did not manage to find anything to match what i need.

Upvotes: 1

Views: 237

Answers (2)

Oto Shavadze
Oto Shavadze

Reputation: 42793

If I correctly understand, you need something like:

select entry_id, content::text from TABLEB where entry_id = ?
union all
select entry_id, content::text from TABLEC where entry_id = ?
union all
select entry_id, content::text from TABLED where entry_id = ?

Upvotes: 1

JohnHC
JohnHC

Reputation: 11205

If it can only exist in one table at a time, use a union

select a1.entry_id, b2.content
from TableA a1
inner join TableB b2
on a1.entry_id = b2.entry_id

union -- This removes any duplicates. Use UNION ALL to show duplicates

select a1.entry_id, c3.content::text
from TableA a1
inner join TableC c3
on a1.entry_id = c3.entry_id

Upvotes: 1

Related Questions