开发者

DELETE Difference NOT IN vs NOT EXISTS

I have two scenarios represented below, SCENARIO 1 works as well as SCENARIO 2 but are both those SCENARIOS achieving the Same Objective, Note in both Scenario's otherTbl is static

SCENARIO 1

CREATE TABLE `tbl`(
    col1 VARCHAR(255),

    PRIMARY KEY(col1)
) ENGINE='InnoDb';

Here is my set of queries that I run previously that make sense and run fine.

#Create an exact copy of the `tbl`
CREATE TEMPORARY TABLE `tmp_tbl`( .. SAME AS `tbl` .. );

#Add grouped records from another table into `tmp_tab开发者_如何学Cle`
INSERT INTO tmp_tbl SELECT col1 FROM otherTbl GROUP BY col1;

#Delete the tables that donot exist any more int the `otherTbl`
DELETE FROM tbl WHERE tbl.col1 NOT IN (SELECT col1 FROM tmp_tbl);

SCENARIO 2

In this scenario the difference is only of the columns, As you can see all of them are primary Keys

CREATE TABLE `tbl`(
    col1 VARCHAR(255),
    col2 VARCHAR(255),
    col3 VARCHAR(255),

    PRIMARY KEY(col1, col2, col3)
) ENGINE='InnoDb';

Here are the new set of Queries

#Create an exact copy of the `tbl`
CREATE TEMPORARY TABLE `tmp_tbl`( .. SAME AS `tbl` .. );

#Add grouped records from another table into `tmp_table`
INSERT INTO tmp_tbl 
    SELECT col1, col2, col3 FROM otherTbl GROUP BY col1, col2, col3;

#Delete the tables that donot exist any more int the `otherTbl`
DELETE FROM tbl WHERE NOT EXISTS(SELECT col1, col2, col3 FROM `tmp_tbl`);

The question simply is, Do they achieve the same conclusion HENCE if we replace the delete query from NOT IN to NOT EXISTS in SCENARIO 1 it will still work the same way.

******SIMPLE VERSION******

Is:

DELETE FROM `tbl` WHERE tbl.col1 NOT IN (SELECT col1 FROM tmp_tbl);

Equall To:

DELETE FROM `tbl` WHERE NOT EXISTS(SELECT col1 FROM `tmp_tbl`);


I haven't tested it, but they are most likely not equivalent. The NOT EXISTS form would make sense if used with a correlated subquery. But your subquery doesn't contain any reference to the outer query, so probably the second form won't delete any rows at all.

Also, presence of NULLs in the table may make these two forms act very differently.


These two queries should, to my knowledge, achieve the same results (since the query checks for the same data - only the second one does it in a more elegant manner maybe).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜