问题
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!
回答1:
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;
来源:https://stackoverflow.com/questions/21552299/changing-a-sql-query-using-join-instead-of-a-subselect