如果column1值存在于column1中的任何位置,则删除行

时间:2017-05-26 19:45:45

标签: sql exists

程序以如下表格开头:

kafkaProduc.send("topictest", msg).addCallback(
                new ListenableFutureCallback<SendResult<String, ExecutionDataMessage>>() {
    @Override
    public void onSuccess(SendResult<String, ExecutionDataMessage> result) {
        eresp.status = "ok";
        eresp.msg = "message submitted successfully";
    }

    @Override
    public void onFailure(Throwable ex) {
        eresp.status = "error";
        eresp.msg = "failure while sending data to kafka. exception: " + ex.getMessage();
    }
});
HttpStatus erespStatus = eresp.status == "ok" ? HttpStatus.CREATED : HttpStatus.BAD_REQUEST;
return new ResponseEntity<ExecutionResponse>(eresp, erespStatus);

指示程​​序根据现有行中的信息创建新行。 copyID字段包含从中复制数据的行的ID。复制第1行和第2行后,新表格如下所示:

ID   data1   data2   ...   copyID
15      a       b           NULL
16      c       d            11

现在,我想只选择不是&#t;&#34;重复&#34;的行。我们已经捕获的行数。由于ID 15是&#34;原创,&#34;应该保持。由于没有ID = 11,我们想要维护ID 16.因为我们已经有ID = 15和ID = 16,所以我们不需要ID = 17或ID = 18.在SQL中处理这个决策的过程是什么?

3 个答案:

答案 0 :(得分:2)

我认为以下代码可以解决您的问题:

select      a.*
from        yourtable a
left join   yourtable b
on          a.copid = b.id
where       b.id is null

答案 1 :(得分:0)

您可以使用EXISTS

例如:

declare  @T table (ID int, data1 varchar(30), data2 varchar(30), copyID int);

-- adding the parent records
insert into @T (ID, data1, data2, copyID) values
(15,'a','b',NULL),
(16,'c','d',11);

-- adding the duplicates
insert into @T (ID, copyID, data1, data2)
select m.maxID + row_number() over (order by id) as newID, t.ID as copyID, t.data1, t.data2
from @T t
cross apply (select max(id) as maxID from @T) m;

-- Only selecting those the parent record does not exist
select * 
from @T t1 
where not exists (
    select 1 
    from @T t2
    where t1.copyID = t2.ID
    and t1.data1 = t2.data1 and t1.data2 = t2.data2
);

-- Or via a LEFT JOIN and keeping those that are only on the left side
select t1.* 
from @T t1
left join @T t2 on (t1.copyID = t2.ID and t1.data1 = t2.data1 and t1.data2 = t2.data2)
where t2.ID is null;

返回:

ID data1 data2 copyID
15 a     b     NULL
16 c     d     11

答案 2 :(得分:0)

这是一个简单的exists

select t.*
from t
where t.copyid is null or
      not exists (select 1 from t t2 where t2.id = t.copyid);

这会处理NULL案例和NOT EXISTS案例。

这可以简化为:

select t.*
from t
where not exists (select 1 from t t2 where t2.id = t.copyid);