Changing a sql query using join instead of a subselect

此生再无相见时 提交于 2019-12-12 01:08:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!