简体   繁体   中英

Changing a sql query using join instead of a subselect

i've got the following problem: Because the amount of entries could get very big, I would like to use a join instead of a subselect in a sql query.

It regards the following three simplified tables:

devices:
- id

confirmation_requests:
- id
- filePath

confirmation
- id
- requestId (references confirmation_requests.id)
- deviceId (references devices.id)

The target is, to get all confirmation requests, which are not confirmed (with an entry in the confirmation table) by a given device.

I just come to a solution using an ordinary subquery, an example you find here: http://sqlfiddle.com/#!2/13fd3/1

SELECT * 
FROM confirmation_requests 
WHERE id NOT IN (SELECT confirmation_request_id
                     FROM confirmations
                     WHERE device_id = 1);

Thanks!

You can do a LEFT JOIN onto the table for confirmations matching device_id = 1 then exclude those in the WHERE clause:

SELECT cr.* 
FROM confirmation_requests cr
LEFT JOIN confirmations c ON (cr.id = c.confirmation_request_id AND c.device_id = 1)
WHERE c.id IS NULL;

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