基于另一个表从一个表中排序数据

时间:2014-02-19 20:23:18

标签: sql sql-server-2008 select sql-order-by

以下是我的表格:

create table tableA (id int, type varchar(5))
insert into tableA (ID,TYPE)
values

    (101,'A'),
    (101,'C'),
    (101,'D'),
    (102,'A'),
    (102,'B'),
    (103,'A'),
    (103,'C')

create table tableB (id int, type varchar(5), isActive bit)
insert into tableB (id, type, isActive)
Values 

    (101,'A',1),
    (101,'B',0),
    (101,'C',0),
    (101,'D',1),

    (102,'A',1),
    (102,'B',0),
    (102,'C',1),
    (102,'D',1),

    (103,'A',1),
    (103,'B',1),
    (103,'C',1),
    (103,'D',1)

现在,我想在这里做两件事: 1)在tableA中查找isActive = 0tableB中存在的行。 (完成)

select A.* from tableA A
join tableB B
on A.id = B.id and A.type = B.type 
where B.isactive = 0  

2)在tableA中查找isActive = 1tableB中缺少的行。 例如ID 103,类型B在tableB中处于活动状态,但在tableA中缺失。 我并不关心tableA中D类型的存在,因为我只检查tableA中的最后一个条目,即C. 此外,ABCD适用于所有ID,它们可以是活动的或非活动的。

感谢您的帮助!

我的努力:(不工作)

select A.* from tableA A
where exists (
select B.* from tableA A
join tableB B 
on a.id = b.id 
where b.isActive = 1
order by b.id,b.type
)

SQLFiddle

1 个答案:

答案 0 :(得分:2)

我认为您正在寻找以下内容:

select B.* from tableB B
left join tableA A
  on B.id = A.id and B.type = A.type
where B.isActive = 1
  and A.id is null
order by B.id, B.type

通过使用左连接,这意味着tableB中没有要在tableA中连接的行的行将使所有A. *列为null。然后,这允许您添加where子句以检查tableA记录为null的位置,从而确定tableB中包含的活动而不是tableA中的内容