簡體   English   中英

SELECT項目列表中的子查詢的SQL替代方法

[英]SQL alternative to sub-query in SELECT Item list

我有完美的RDBMS表和查詢。 我已將數據從RDBMS卸載到HIVE表。要在HIVE上運行現有查詢,我們首先需要使它們與HIVE兼容。

讓我們在選擇項列表中以子查詢為例。 它在語法上是有效的,並且在RDBMS系統上運行良好。 但它不適用於HIVE根據HIVE手冊 ,Hive僅支持FROM和WHERE子句中的子查詢。

例1:

SELECT t1.one
    ,(SELECT t2.two 
        FROM TEST2 t2 
        WHERE t1.one=t2.two) t21
    ,(SELECT t3.three 
        FROM TEST3 t3 
        WHERE t1.one=t3.three) t31
FROM TEST1 t1 ;

例2:

SELECT a.*
   , CASE
          WHEN EXISTS
                 (SELECT 1
                    FROM tblOrder O
                      INNER JOIN tblProduct P
                              ON O.Product_id = P.Product_id
                   WHERE O.customer_id        = C.customer_id
                     AND P.Product_Type IN (2, 5, 6, 9)
                 )
          THEN 1
          ELSE 0
   END AS My_Custom_Indicator
   FROM tblCustomer C
   INNER JOIN tblOtherStuff S
       ON C.CustomerID = S.CustomerID ;

例3:

Select component_location_id, component_type_code,
  ( select clv.LOCATION_VALUE 
  from stg_dev.component_location_values clv 
  where  identifier_code = 'AXLE' 
       and component_location_id = cl.component_location_id ) as AXLE,
  ( select clv.LOCATION_VALUE 
  from stg_dev.component_location_values clv 
  where identifier_code = 'SIDE' 
       and component_location_id = cl.component_location_id ) as SIDE
  from stg_dev.component_locations cl ;

我想知道選擇項列表中可能的子查詢替代方法,以使其與hive兼容。 顯然,我將能夠轉換HIVE格式的現有查詢。

任何幫助和指導都非常感謝!

您提供的查詢可以轉換為使用LEFT JOIN的簡單查詢。

SELECT
  t1.one, t2.two AS t21, t3.three AS t31
FROM
  TEST1 t1
  LEFT JOIN TEST2 t2
    ON t1.one = t2.two
  LEFT JOIN TEST3 t3
    ON t1.one = t3.three

由於子查詢沒有限制,連接將返回相同的數據。 (對於TEST1中的每一行,子查詢應該只返回一行或沒有行。)

請注意,您的原始查詢無法處理1..n連接。 在大多數DBMS中,SELECT列表中的子查詢應僅返回具有一列和一行或沒有行的結果集。

基於HIVE手冊

SELECT t1.one, t2.two, t3.three 
FROM TEST1 t1,TEST2 t2, TEST3 t3
WHERE t1.one=t2.two AND t1.one=t3.three;
    SELECT t1.one,t2.two,t3.three FROM TEST1 t1 INNER 
   JOIN TEST2 t2 ON t1.one=t2.two INNER JOIN TEST3 t3 
   ON t1.one=t3.three WHERE t1.one=t2.two AND t1.one=t3.three;
SELECT t1.one,t2.two as t21,t3.three as t31 FROM TEST1 t1 
INNER JOIN TEST2 t2 ON t1.one=t2.two
INNER JOIN TEST3 t3 ON t1.one=t3.three

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM