繁体   English   中英

T-SQL 逻辑(存在一列但不存在另一列)

[英]T-SQL Logic (Where exists one column but not the other)

我需要一些逻辑上的帮助来编写查询。

这是设置。

create table main_table 
(
    id varchar(10) not null,
    seq varchar(10) not null
)

insert into main_table (id, seq) 
values ('A1', '1'), ('A1', '2'),
       ('A1', '3'), ('A2', '1'),
       ('A2', '2'), ('A2', '3'),
       ('A3', '1'), ('A3', '2'),
       ('A3', '3');
go

create table sub_table 
(
    id varchar(10) not null,
    seq varchar(10) not null
)

insert into sub_table (id, seq) 
values ('A1', '1'), ('A1', '2'), ('A2', '1');

我需要一个查询,从返回的所有记录main_table其中idmain_table匹配的idsub_table ,但seqmain_table不匹配seqsub_table

预期结果是

ID 序列
A1 3
A2 2
A2 3

我的尝试

select
    a.id, a.seq 
from 
    main_table a
where 
    exists (select 1 from sub_table b
            where a.id = b.id and a.seq != b.seq)

执行此操作的正确查询是什么?

这是一种方法( 小提琴

SELECT a.id,
       a.seq
FROM   main_table a
       JOIN sub_table b
         ON a.id = b.id
GROUP  BY a.id,
          a.seq
HAVING MAX(CASE WHEN a.seq = b.seq THEN 1 ELSE 0 END) = 0 

或者

SELECT a.id,
       a.seq
FROM   main_table a
WHERE  a.id IN (SELECT b.id
                FROM   sub_table b)
       AND NOT EXISTS (SELECT 1
                       FROM   sub_table b
                       WHERE  a.id = b.id
                              AND a.seq = b.seq) 

尝试这个

select * from main_table M 
inner join sub_table S on M.id = S.id
where M.seq  <> S.seq

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM