Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Same sub-query used multiple times in a single query

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.

like image 933
Talha Ahmed Khan Avatar asked Jun 12 '13 11:06

Talha Ahmed Khan


People also ask

How many subqueries can be used in a single SQL statement?

A subquery can itself include one or more subqueries. Any number of subqueries can be nested in a statement.

How many times will the subquery be executed?

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.

Can you have 2 subqueries in a SELECT statement?

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.

What is a nested sub query?

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.


1 Answers

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 ...
      ) ;
like image 167
ypercubeᵀᴹ Avatar answered Dec 11 '22 02:12

ypercubeᵀᴹ