需要查询而不使用子查询

时间:2013-09-05 11:58:32

标签: sql oracle subquery

我的桌子是

PROPOSAL_TABLE
  PID   QUOTE_ID   PDF1
  ---   --------   ----
   1       123      null
   2       123      null
   3       123      null
   4       152      null
   5       888      null

我需要选择MAX PID引用ID。 我有一个问题:

 SELECT PROPOSAL_PDF FROM PROPOSAL_TBL WHERE QUOTE_ID = '123' 
 AND PID = (SELECT MAX(PID) FROM PROPOSAL_TBL WHERE QUOTE_ID = '123')  

如何在不使用子查询的情况下获取值?

4 个答案:

答案 0 :(得分:2)

不使用子查询,您可以使用KEEP子句:

select max(pid) as pid
     , max(quote_id) keep ( dense_rank first order by pid desc ) as quote_id
     , max(pdf1) keep ( dense_rank first order by pid desc ) as pdf1
  from proposal_table
 where quote_id = '123'

这应该是高效的,但一如既往地测试。我建议阅读Rob van Wijk's博客文章。

标准替代方案是使用子查询但不需要使用分析函数对表进行另一次扫描,例如: ROW_NUMBER()

select pid, quote_id, pdf1
  from ( select a.*, row_number() over ( order by pid ) as rn 
           from proposal_table a
          where quote_id = '123' )
 where rn = 1

答案 1 :(得分:1)

您可以使用analytics

SQL> WITH DATA AS (
  2            SELECT 1 pid, 123 quote_id, 'A' pdf1 FROM DUAL
  3  UNION ALL SELECT 2 pid, 123 quote_id, 'B' pdf1 FROM DUAL
  4  UNION ALL SELECT 3 pid, 123 quote_id, 'C' pdf1 FROM DUAL
  5  UNION ALL SELECT 4 pid, 152 quote_id, 'D' pdf1 FROM DUAL
  6  UNION ALL SELECT 5 pid, 888 quote_id, 'E' pdf1 FROM DUAL
  7  )
  8  SELECT DISTINCT first_value(pid) over (ORDER BY pid DESC) pid,
  9                  quote_id,
 10                  first_value(pdf1) over (ORDER BY pid DESC) pdf1
 11    FROM DATA
 12   WHERE quote_id = 123;

       PID   QUOTE_ID PDF1
---------- ---------- ----
         3        123 C

您还可以使用aggregates

SQL> WITH DATA AS (
  2            SELECT 1 pid, 123 quote_id, 'A' pdf1 FROM DUAL
  3  UNION ALL SELECT 2 pid, 123 quote_id, 'B' pdf1 FROM DUAL
  4  UNION ALL SELECT 3 pid, 123 quote_id, 'C' pdf1 FROM DUAL
  5  UNION ALL SELECT 4 pid, 152 quote_id, 'D' pdf1 FROM DUAL
  6  UNION ALL SELECT 5 pid, 888 quote_id, 'E' pdf1 FROM DUAL
  7  )
  8  SELECT MAX(pid),
  9         quote_id,
 10         MAX(pdf1) KEEP (DENSE_RANK FIRST ORDER BY pid DESC) pdf1
 11    FROM DATA
 12   WHERE quote_id = 123
 13   GROUP BY quote_id;

  MAX(PID)   QUOTE_ID PDF1
---------- ---------- ----
         3        123 C

答案 2 :(得分:-1)

试试这个::

SELECT PROPOSAL_PDF 
FROM PROPOSAL_TBL WHERE QUOTE_ID = '123' 
ORDER BY  PID desc limit 1

答案 3 :(得分:-1)

Sql Server

SELECT TOP 1 PROPOSAL_PDF  
FROM PROPOSAL_TBL 

WHERE QUOTE_ID = '123' 
ORDER BY  PID desc

Oracle

SELECT * from (Select * FROM PROPOSAL_TBL 
               WHERE QUOTE_ID = '123' 
               ORDER BY  PID desc)
WHERE ROWNUM <=1