PostgreSQL 'NOT IN' and subquery

后端 未结 3 1153
我寻月下人不归
我寻月下人不归 2020-12-13 03:14

I\'m trying to execute this query:

SELECT mac, creation_date 
FROM logs 
WHERE logs_type_id=11
AND mac NOT IN (select consols.mac from consols)
相关标签:
3条回答
  • 2020-12-13 03:45

    When using NOT IN, you should also consider NOT EXISTS, which handles the null cases silently. See also PostgreSQL Wiki

    SELECT mac, creation_date 
    FROM logs lo
    WHERE logs_type_id=11
    AND NOT EXISTS (
      SELECT *
      FROM consols nx
      WHERE nx.mac = lo.mac
      );
    
    0 讨论(0)
  • 2020-12-13 03:54

    When using NOT IN you should ensure that none of the values are NULL:

    SELECT mac, creation_date 
    FROM logs 
    WHERE logs_type_id=11
    AND mac NOT IN (
        SELECT mac
        FROM consols
        WHERE mac IS NOT NULL -- add this
    )
    
    0 讨论(0)
  • 2020-12-13 04:00

    You could also use a LEFT JOIN and IS NULL condition:

    SELECT 
      mac, 
      creation_date 
    FROM 
      logs
        LEFT JOIN consols ON logs.mac = consols.mac
    WHERE 
      logs_type_id=11
    AND
      consols.mac IS NULL;
    

    An index on the "mac" columns might improve performance.

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