简体   繁体   中英

Additional condition used for filtering only on some type of columns

Here's my use-case: I 'd like to filter out all records on one condition and additionally filter out some records on additional condition.

EDITED

Here's the two conditions:

  1. all records must met condition created_at > SYSDATE + 30
  2. records from the table users that have (share) the same id as in the table blacklist ( join on u.id = b.id ) where the column endpoint is equal to XYZ must have column delayed_until that meets criterion older than now . If endpoint is not equal to XYZ , only 1st condition applies.

I have come up with the following query:

SELECT    * users u 
left join blacklist b 
ON        u.id = b.id 
AND       b.delayed_until < SYSDATE 
AND       u.endpoint = 'XYZ' 
WHERE     u.created_at > SYSDATE + 30;

Here's my schema (simplified):

在此处输入图片说明

Does my query do what intended? Can it be rewritten so that it is faster? If so, how?

I think this is what you want:

SELECT *
FROM users u JOIN
     blacklist b 
     ON u.id = b.id AND
        (b.delayed_until <= SYSDATE OR
         u.endpoint <> 'XYZ'
        )      
WHERE u.created_at > SYSDATE + 30;

Filtering on the first table in the ON clause doesn't make sense with a LEFT JOIN .

For this query, you want indexes on users(endpoint, created_at, id) and blacklist(id, delayed_until) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM