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

后端 未结 3 648
醉酒成梦
醉酒成梦 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:47

    Try using joins

    Select count(Table1_delta.pagename) from Table1_delta 
    INNER JOIN Table1 ON 
        Table1_delta.pagename != Table1 .pagename 
        AND Table1.status != 1
    
    0 讨论(0)
  • 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 (<subquery>)) 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.

    0 讨论(0)
  • 2021-01-19 16:06

    Here is an alternative solution using joins:

    SELECT COUNT(*)
    FROM Table1_delta t1 LEFT JOIN Table1 t2
    ON t1.pagename = t2.pagename
    WHERE t2.status IS NULL OR t2.status = 1
    

    Here is what the temporary table from the above query looks like:

    +-----------+--------+
    | pagename  | status |
    +-----------+--------+
    | pagename1 |  2     |    # this row is NOT counted
    | pagename2 |  1     |    # +1 this row has status = 1 and is counted
    | pagename3 |  null  |    # +1 this row has status = null and is counted
    | pagename4 |  null  |    # +1 this row is also null and is counted
    +-----------+--------+
    

    Check out the link below for a running demo.

    SQLFiddle

    0 讨论(0)
提交回复
热议问题