Select from different tables

Asked

Viewed 61 times

0

How to select from different tables? Type, check if there is value in one, if not, check in the other.

  • post the structure of your tables and what you have tried to do

1 answer

2


Although the question does not make explicit the context, I will try to answer in the most general way possible (although for me it is almost impossible not to think about Postgresql. :-))

Let’s say we have the following scheme

CREATE TABLE Table1 (
    code char(5) CONSTRAINT firstkey PRIMARY KEY);

CREATE TABLE Table2 (
    code char(5) CONSTRAINT secondkey PRIMARY KEY);

And the following inserts:

INSERT INTO Table1 VALUES ('1');
INSERT INTO Table1 VALUES ('2');
INSERT INTO Table1 VALUES ('3');

INSERT INTO Table2 VALUES ('1');
INSERT INTO Table2 VALUES ('2');
INSERT INTO Table2 VALUES ('3');
INSERT INTO Table2 VALUES ('4');
INSERT INTO Table2 VALUES ('5');

Let’s say we need to retrieve the code='5', but we don’t know what tabala it’s in, so one way would be:

SELECT code FROM Table2 WHERE code='5' and code NOT IN 
    (SELECT code FROM Table1 where code='5')  

If I understand the question correctly, this is one way.

  • Embedding that for each row of the table code DB will run subselect (SELECT code FROM Table1 Where code='5')

Browser other questions tagged

You are not signed in. Login or sign up in order to post.