Count all records that does not exist to other table - SQL Query

后端 未结 3 649
醉酒成梦
醉酒成梦 2021-01-19 15:30

I have two(2) tables and I\'m trying to count all records from Table1 and Table1_delta were pagename from Table1_delta is not yet listed into Table1. Incase pagename from Ta

3条回答
  •  遥遥无期
    2021-01-19 15:53

    If I've understood correctly:

    SELECT COUNT(*) FROM Table1_Delta
    WHERE pagename NOT IN 
      (SELECT pagename FROM Table1 WHERE status = 1)
    

    Update

    As requested in the comments, here's what this query does:

    First, the subquery: SELECT pagename FROM Table1 WHERE status = 1, retrieves the pagename field from those Table1 records where status is 1.

    So in the example case, it'll return a single row, containing pagename2.

    Then the main query counts all the records in Table1_Delta (SELECT COUNT(*) FROM Table1_Delta) whose Pagename does not contain (WHERE Pagename NOT IN ()) those values returned from the subquery.

    So this would match 3 entries (pagename1, pagename3, pagename4), and that's the count you get

    Historically, using sub-queries is considered slower than using joins, but frankly, RDBMS's have come a long way optimizing queries, and for simple cases like this, it would be "probably" (I haven't measured) faster. It actually depends on the real case and DB... but the SQL code is much more self-explanatory than joins IMO. Your mileage may vary.

提交回复
热议问题