Re: [GENERAL] Select from tableA - if not exists then tableB

Поиск
Список
Период
Сортировка
От Brian Dunavant
Тема Re: [GENERAL] Select from tableA - if not exists then tableB
Дата
Msg-id CAJTy2ekMUXDY1MQnq-K+J=qRiVuc-FDykZ5KmNKSqznLK1MQsg@mail.gmail.com
обсуждение исходный текст
Ответ на [GENERAL] Select from tableA - if not exists then tableB  (Patrick B <patrickbakerbr@gmail.com>)
Ответы Re: [GENERAL] Select from tableA - if not exists then tableB  (Patrick B <patrickbakerbr@gmail.com>)
Список pgsql-general
From what you're saying about migrating, I'm assuming the new table
has additional columns or something.  If you can map the difference,
then you could use CTE's to select from the first table, and if
nothing is there, then pull from the second table and pad it with
nulls so they "match".  This should work fine in 9.1.

For example:

db=# create table old ( id integer );
CREATE TABLE
db=# create table new ( id integer, newcol text );
CREATE TABLE
db=# insert into old (id) values (1), (2);
INSERT 0 2
db=# insert into new (id, newcol) values (1, 'a');
INSERT 0 1

New table:

db=# with new_check as (
db(#   select id, newcol from new where id = 1
db(# )
db-# select id, null::text as newcol from old where id = 1
db-# and not exists ( select 1 from new_check )
db-# union all
db-# select * from new_check;
 id | newcol
----+--------
  1 | a
(1 row)

Old table:

db=# with new_check as (
db(#   select id, newcol from new where id = 2
db(# )
db-# select id, null::text as newcol from old where id = 2
db-# and not exists ( select 1 from new_check )
db-# union all
db-# select * from new_check;
 id | newcol
----+--------
  2 |
(1 row)

Neither:

db=# with new_check as (
db(#   select id, newcol from new where id = 3
db(# )
db-# select id, null::text as newcol from old where id = 3
db-# and not exists ( select 1 from new_check )
db-# union all
db-# select * from new_check;
 id | newcol
----+--------
(0 rows)





On Mon, May 8, 2017 at 5:56 PM, Patrick B <patrickbakerbr@gmail.com> wrote:
> Hi guys,
>
> I have two tables that supports the same data, but different table DDL (We
> are migrating all the data from one to another).
>
> What I need is basically:
>
> 1. Query looks for the data on table A,
> 2. if it doesn't find it on table A, go look for it on table B
>
> Now, how could I do that in a Select? Can you please provide some examples?
>
>
> I'm using PostgreSQL 9.1.
>
> Thanks
> Patrick


В списке pgsql-general по дате отправления:

Предыдущее
От: David Rowley
Дата:
Сообщение: Re: [GENERAL] Select from tableA - if not exists then tableB
Следующее
От: Alvaro Herrera
Дата:
Сообщение: [GENERAL] [plncek2@gmail.com: Can I safe my Data?]