ПРИСОЕДИНЯЙТЕСЬ к таблицам, оценивая результаты одного из них

0

У меня есть три таблицы, чтобы присоединиться, один из них с одним-несколькими значениями.

SQLFIDDLE

CREATE TABLE Table1  ('id' int, 'name' varchar(3));

INSERT INTO Table1   ('id', 'name')
VALUES   (1, 'A'),  (2, 'B'),   (3, 'C');


CREATE TABLE Table2   ('id' int, 'status' int, 'date' varchar(9));

INSERT INTO Table2  ('id', 'status', 'date')
VALUES   (1, 1, '''.11..'''),  (1, 2, '''.12..'''),   (1, 3, '''.13..'''),
         (2, 3, '''.23..'''),  (3, 1, '''.31..'''),   (3, 3, '''.33..''')
;


CREATE TABLE Table3  ('id' int, 'value' int);

INSERT INTO Table3   ('id', 'value')
VALUES     (1, 34),  (2, 22),  (3, 17);

Запрос 1:

select * from table1

| id | name |
|----|------|
|  1 |    A |
|  2 |    B |
|  3 |    C |

Запрос 2:

select * from table2;

| id | status |    date |
|----|--------|---------|
|  1 |      1 | '.11..' |
|  1 |      2 | '.12..' |
|  1 |      3 | '.13..' |
|  2 |      3 | '.23..' |
|  3 |      1 | '.31..' |
|  3 |      3 | '.33..' |

Запрос 3:

select * from table3

| id | value |
|----|-------|
|  1 |    34 |
|  2 |    22 |
|  3 |    17 |

Мне нужен запрос, который возвращает для каждого id:

   TABLE1.name, TABLE2.status, TABLE2.date, TABLE3.value

с этим условием:

  • Если TABLE2.status = 1 существует, верните ТОЛЬКО эту строку TABLE2
  • Else, если TABLE2.status = 1 не существует, ищите статус = 2 и возвращайте ТОЛЬКО эту строку TABLE2
  • Если ни одно из этих значений не присутствует в TABLE2, то пропустите этот идентификатор из результатов

EDIT: TABLE2 имеет UNIQUE ключ для id, статус, поэтому может быть только один id = 1 status = 1

Спасибо за вашу помощь!

  • 1
    Есть ли УНИКАЛЬНОЕ ограничение на table2 (id, status) ? Может ли быть больше одной строки в table2 которая удовлетворяет условию id=1 status=1 или у нас есть гарантия, что будет не более одной строки?
  • 0
    @spencer7593 spencer7593 В таблице 2 только один идентификатор = 1 статус = 1
Показать ещё 4 комментария
Теги:

2 ответа

3
Лучший ответ

Что-то вроде этого может быть:

select table1.id, table1.name,
    coalesce(table2_status1.status, table2_status2.status) as status,
    coalesce(table2_status1.date, table2_status2.date) as date,
    table3.value
from table1
left join table2 table2_status1 on table2_status1.id = table1.id and table2_status1.status = 1
left join table2 table2_status2 on table2_status2.id = table1.id and table2_status2.status = 2
join table3 on table3.id = table1.id
where (table2_status1.id is not null or table2_status2.id is not null);
  • 1
    coalesce(table2_status1.status, table2_status2.status) as status, coalesce(table2_status1.date, table2_status2.date) as date ? - твой лучше,
  • 0
    @PatrickArtner Спасибо. Хорошая идея для объединения, я не сразу подумал об этом.
Показать ещё 11 комментариев
0

Не работает, используя подзапросы, работает (но rlanvins qaru.site/questions/14978167/... лучше):

A, B, C вместо First, Second...

select 
    TABLE1.name,

    case 
      when exists( select 1 from table2 where id = table1.id and status = 1)
        then 1
      when exists( select 1 from table2 where id = table1.id and status = 2)
        then 2 
    end as T2status,

    case 
      when exists( select 1 from table2 where id = table1.id and status = 1)
        then ( select date from table2 where id = table1.id and status = 1)
      when exists( select 1 from table2 where id = table1.id and status = 2)
        then ( select date from table2 where id = table1.id and status = 2)
    end as T2date,

    TABLE3.value
from table1
join table3 on table1.id = table3.id
where     
    exists( select 1 from table2 where id = table1.id and status = 1)
    or exists( select 1 from table2 where id = table1.id and status = 2)

Выход

Name    T2status    T2date  value
A       1           '.11..' 34 
C       1           '.31..' 17

DDL

CREATE TABLE Table1  ('id' int, 'name' varchar(3));

INSERT INTO Table1   ('id', 'name')
VALUES   (1, 'A'),  (2, 'B'),   (3, 'C');


CREATE TABLE Table2   ('id' int, 'status' int, 'date' varchar(9));

INSERT INTO Table2  ('id', 'status', 'date')
VALUES   (1, 1, '''.11..'''),  (1, 2, '''.12..'''),   (1, 3, '''.13..'''),
         (2, 3, '''.23..'''),  (3, 1, '''.31..'''),   (3, 3, '''.33..''')
;


CREATE TABLE Table3  ('id' int, 'value' int);

INSERT INTO Table3   ('id', 'value')
VALUES     (1, 34),  (2, 22),  (3, 17);
  • 0
    Проще читать за меня :) спасибо тоже!

Ещё вопросы

Сообщество Overcoder
Наверх
Меню