I am running a query that contains same sub-query used multiple times in a WHERE
clause.
I have a table having tow fields client_id
, buyer_id
.
The sub-query returns the list of dates to be excluded from the result.
This is how I am using it.
SELECT
id, client_id, buyer_id
FROM relation
WHERE
client_id NOT IN (SELECT <some_id> FROM <some_table> WHERE ...)
AND buyer_id NOT IN (SELECT <some_ids> FROM <some_table> WHERE ...)
This is working as expected but what bothers me that there are two same sub-queries. I wonder if there is a way that I can use it once and use the result for both places.
Thanks.
A subquery can itself include one or more subqueries. Any number of subqueries can be nested in a statement.
A correlated SQL subquery is just a subquery that is executed many times—once for each record (row) returned by the outer (main) query. In other words, the outer query returns a table with multiple rows; the inner query then runs once for each of those rows.
More formally, it is the use of a SELECT statement inside one of the clauses of another SELECT statement. In fact, a subquery can be contained inside another subquery, which is inside another subquery, and so forth. A subquery can also be nested inside INSERT, UPDATE, and DELETE statements.
A Subquery or Inner query or a Nested query is a query within another SQL query and embedded within the WHERE clause. A subquery is used to return data that will be used in the main query as a condition to further restrict the data to be retrieved.
You can write this using NOT EXISTS
:
SELECT
id, client_id, buyer_id
FROM relation AS r
WHERE NOT EXISTS
( SELECT 1
FROM <some_table>
WHERE (r.client_id = <some_id> OR r.buyer_id = <some_id>)
AND ...
) ;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With