Запрос, который возвращает похожие и разные строки из двух таблиц, которые не имеют отношений - PullRequest
0 голосов
/ 10 мая 2018

У меня есть две таблицы с несколькими столбцами, но я забочусь только о двух столбцах (profile1 и profile2).Ни одна таблица не имеет отношения к другой.Я хотел бы видеть, существуют ли

  • profile1 и profile2 и в table1, и в table2
  • profile1 и profile2 и в table1, но не в table2
  • profile1 иоба profile2 существуют в table2, но не в table1

table 1

profile1 profile2

table 2

profile1 profile2 

Я не уверен, что делаюэто правильно.

profile1 и profile2 существуют в table1 и table2

SELECT DISTINCT T2.profile1, T2.profile2
    FROM table2 as T2
WHERE  EXISTS
(
    SELECT DISTINCT T1.profile, T1.profile2
FROM table1 as T1

    WHERE T2.profcode = T1.profcode 
    AND T2.connecting_profcode = T1.connecting_profcode
);

Существует в T1, но не в T2

SELECT DISTINCT T2.profile1, T2.profile2
    FROM table2 as T2
WHERE NOT EXISTS
(
    SELECT DISTINCT DISTINCT T1.profile1, T1.profile2
FROM table1 as T1

    WHERE T2.profile1 = T1.profile1 
    AND T2.profile2 = T1.profile2
);

Существует в T2, но не в T1

SELECT  DISTINCT T1.profile1, T1.profile2
FROM table1 as T1
WHERE NOT EXISTS
(
    SELECT DISTINCT T2.profile1, T2.profile2
    FROM table2 as T2
    WHERE T1.profile1 = T2.profile1 
    AND T1.profile2 = T2.profile2
);

Ответы [ 2 ]

0 голосов
/ 10 мая 2018

Вы также можете сделать это следующим образом:

Select  
*,
ExistsInT1= Case when t2p1 is NULL AND t1p1 IS NOT NULL then 1 else 0 end,
ExistsInT2= Case when t1p1 is NULL AND t2p1 IS NOT NULL then 1 else 0 end,
ExistsInBoth= Case when t1p1 IS NOT NULL AND t2p1 IS NOT NULL then 1 else 0 end
from (


    select t1.Profile1 as T1P1, t1.Profile2 as T1P2, T2.profile1 as T2p1,
t2.profile2 as t2p2 from table1 t1 left outer join table2 t2
    on t1.profile1=t2.profile1 and t2.profile2=t1.profile2
union 
     select t1.Profile1 as T1P1, t1.Profile2 as T1P2, T2.profile1 as T2p1,
t2.profile2 as t2p2  from table1 t1 right outer join table2 t2
    on t1.profile1=t2.profile1 and t2.profile2=t1.profile2
) T
0 голосов
/ 10 мая 2018

Вы хотите, чтобы отдельный оператор SELECT

1.profile1 и profile2 оба существовали и в table1, и в table2

select t1.* 
from table1 t1
where exists (select 1 from table2 where profile1 = t1.profile1 and profile2 = t1.profile2);

2.profile1 и profile2 оба существуют в table1, но не в table2

select t1.* 
from table1 t1
where not exists (select 1 from table2 where profile1 = t1.profile1 and profile2 = t1.profile2);

3.profile1 и profile2 существуют в таблице 2, но отсутствуют в таблице1

select t2.* 
from table2 t2
where not exists (select 1 from table1 where profile1 = t2.profile1 and profile2 = t2.profile2);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...