简体   繁体   中英

Querying many values from database by mutiple column

I have following query:

SELECT
  a, b, value
FROM
  table
WHERE
  a = :a AND b = :b

I have to select a value for N=10000+ different (a, b) pairs.

The most simple solution is to make N single queries, but it sucks from the performance POV. What is more optimal solution for this case?

SELECT
  a, b, value
FROM
  table
WHERE
  (a ,b) in ((a1,b1),(a2,b2),(a3,b3),(a4,b4),(a5,b5)...(an,bn)) 

As you can't create a temporary table, maybe using a CTE instead ?

WITH cte AS ( SELECT 'a1' a, 'b1' b FROM DUAL
              UNION ALL SELECT 'a2' a, 'b2' b FROM DUAL
              UNION ALL SELECT 'a3' a, 'b3' b FROM DUAL
              ..
)
SELECT * FROM T JOIN cte USING (a,b)

I don't remember having used a 10000+ rows CTE though (probably not event in the 1000s). I don't know if this scale wells. Anyway, as about performances, without a proper index you probably can't really hope for something blazing fast.


As a matter of fact, I've just tested it on Oracle XE 11g: you can use a cte with more than 10000 rows. It works. But so sloooowly ... at least on my home test system.

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