Is it possible to get multiple values from a subquery?

后端 未结 7 772
無奈伤痛
無奈伤痛 2021-02-06 22:49

Is there any way to have a subquery return multiple columns in oracle db? (I know this specific sql will result in an error, but it sums up what I want pretty well)



        
7条回答
  •  不思量自难忘°
    2021-02-06 23:03

    Here are two methods to get more than 1 column in a scalar subquery (or inline subquery) and querying the lookup table only once. This is a bit convoluted but can be the very efficient in some special cases.

    1. You can use concatenation to get several columns at once:

      SELECT x, 
             regexp_substr(yz, '[^^]+', 1, 1) y,
             regexp_substr(yz, '[^^]+', 1, 2) z
        FROM (SELECT a.x,
                     (SELECT b.y || '^' || b.z yz
                        FROM b
                       WHERE b.v = a.v)
                        yz
                FROM a)
      

      You would need to make sure that no column in the list contain the separator character.

    2. You could also use SQL objects:

      CREATE OR REPLACE TYPE b_obj AS OBJECT (y number, z number);
      
      SELECT x, 
             v.yz.y y,
             v.yz.z z
        FROM (SELECT a.x,
                     (SELECT b_obj(y, z) yz
                        FROM b
                       WHERE b.v = a.v)
                        yz
                FROM a) v
      

提交回复
热议问题