使用JOIN进行简单的oracle查询

时间:2015-06-27 11:08:21

标签: sql oracle

我想知道最大book.price-orders.saleprice

的订单

我的查询是

SELECT BOOKID
FROM ORDERS, BOOK 
WHERE ORDERS.BOOKID=BOOK.BOOKID 
AND PRICE-SALEPRICE =
  (SELECT MAX(PRICE-SALEPRICE)
   FROM ORDERS, BOOK
   WHERE ORDERS.BOOKID = BOOK.BOOKID);

不知道它有什么问题。请帮帮我

2 个答案:

答案 0 :(得分:1)

至少有一个问题是bookid中的select引用含糊不清。有一些风格问题:

  • 永远不要在FROM子句中使用逗号。始终使用明确的JOIN语法。
  • 使用表别名。
  • 始终限定列名称,以便您知道它们的来源。

所以,这可能有效:

SELECT b.BOOKID
FROM ORDERS o JOIN
     BOOK b
     ON o.BOOKID = b.BOOKID 
WHERE b.PRICE - o.SALEPRICE = (SELECT MAX(b2.PRICE - o2.SALEPRICE)
                               FROM ORDERS o2 JOIN
                                    BOOK b2
                                    ON o2.BOOKID = b2.BOOKID
                              );

注意:我已经对列名进行了限定,但我不得不猜测它们来自哪些表。您可能需要调整表别名。

答案 1 :(得分:0)

如果您只想返回一行,可以使用... KEEP ( DENSE_RANK FIRST OVER ... )查找另一列的最小值(无需自行连接以查找最大值):

SQL Fiddle

Oracle 11g R2架构设置

CREATE TABLE BOOK ( BOOKID, PRICE ) AS
          SELECT 1, 4.00 FROM DUAL
UNION ALL SELECT 2, 2.10 FROM DUAL
UNION ALL SELECT 3, 4.20 FROM DUAL;

CREATE TABLE ORDERS (BOOKID, SALEPRICE ) AS
          SELECT 1, 2.15 FROM DUAL
UNION ALL SELECT 1, 7.00 FROM DUAL
UNION ALL SELECT 1, 6.99 FROM DUAL
UNION ALL SELECT 2, 2.15 FROM DUAL
UNION ALL SELECT 2, 2.10 FROM DUAL
UNION ALL SELECT 2, 1.99 FROM DUAL
UNION ALL SELECT 3, 7.99 FROM DUAL;

查询1

SELECT MIN(b.BOOKID) KEEP ( DENSE_RANK FIRST ORDER BY o.SALEPRICE - b.PRICE DESC ) AS BOOKID
FROM   BOOK b
       INNER JOIN
       ORDERS o
       ON (b.BOOKID = o.BOOKID )

<强> Results

| BOOKID |
|--------|
|      3 |