在子查询中获取Id

时间:2013-01-04 15:07:44

标签: database oracle subquery oracle-apex

我一直在APEX的拍卖网站上工作。对于拍卖网站,我需要做一个概述,显示某人已经购买了哪些产品。很确定这只是我忘了的东西但是如何在以下情况下获得结果:

3桌

Table User
USER_ID
EMAIL

Table Product
PRODUCT_ID
USER_ID

Table Bid
BID_ID
PRODUCT_ID
USER_ID
CREDITS

当然还有更多列,但我认为将它们排除会使表达更容易。

需要的结果

显示Product表中的产品。但只有当前用户的出价最高(Credits)。

到目前为止

我一直在思考/尝试这个,但在子查询结束时继续被杀。

SELECT *
FROM "PRODUCT"
WHERE "PRODUCT_ID" IN (SELECT "PRODUCT_ID" FROM "BID"
                      WHERE "USER_ID" = 
                      (SELECT "USER_ID" FROM "USER"
                      WHERE lower("EMAIL") = lower(:APP_USER)))
  and "PRODUCT_ID" = (SELECT "PRODUCT_ID" FROM "BID"
                      WHERE "CREDITS" =
                     (SELECT MAX("CREDITS") FROM "BID"
                      WHERE "PRODUCT_ID" = ?

* Apex从当前用户返回Emailadress(:APP_USER)

真正的问题始于“和”,因为用户过滤工作正常。我不知道如何获得子查询中的比较(当前)PRODUCT_ID。我很确定如果我在子查询的末尾得到那个值,它就会起作用。

使用Oracle DB。

任何帮助表示赞赏:)

2 个答案:

答案 0 :(得分:1)

试试这个..

SELECT *
FROM PRODUCT p
WHERE p.PRODUCT_ID IN (SELECT PRODUCT_ID FROM BID"
                      WHERE "USER_ID" = 
                      (SELECT "USER_ID" FROM "USER"
                      WHERE lower("EMAIL") = lower(:APP_USER)))
  and "PRODUCT_ID" =  (SELECT "PRODUCT_ID" FROM "BID" b
                      WHERE "CREDITS" =
                     (SELECT MAX("CREDITS") FROM "BID"
                      WHERE b.PRODUCT_ID" = p.product_id));

and "PRODUCT_ID" in (SELECT "PRODUCT_ID" FROM "BID" b
                      WHERE "CREDITS" =
                     (SELECT MAX("CREDITS") FROM "BID"
                      WHERE b.PRODUCT_ID" = p.product_id))

答案 1 :(得分:1)

这样的东西?

SELECT
    p.*
FROM
    Bid b
    JOIN
    -- get the max bid per product
    (SELECT
        PRODUCT_ID, MAX(CREDITS) AS MAX_C
    FROM
        Bid
    GROUP BY
        PRODUCT_ID) m ON b.PRODUCT_ID = m.PRODUCT_ID AND b.CREDITS = m.CREDITS
    JOIN USER u ON b.USER_ID = u.USER_ID
    JOIN Product p ON b.PRODUCT_ID = p.PRODUCT_ID
WHERE
    lower(u.EMAIL) = lower(:APP_USER)));

请注意,如果出价中的点数不是每个产品的唯一商品(但这应该是您拍卖中的商业规则),则可能会出现问题。

修改

从查询长度的角度来看,以下情况可能更好,因为它可以确保您只检查用户实际出价的产品上的胜利,而不是检查所有产品的上述产品。

SELECT
    p.*
FROM
    Bid b
    JOIN
    -- get the max bid per product that the user bid on
    (SELECT
        PRODUCT_ID, MAX(CREDITS) AS MAX_C
    FROM
        Bid b2
        JOIN (
            -- get only the products that the user has bid on
            SELECT
                DISTINCT b1.PRODUCT_ID
            FROM
                Bid b1
                JOIN User u1 ON b1.USER_ID = u1.USER_ID
            WHERE
                lower(u1.EMAIL) = lower(:APP_USER))) dp
        ON b2.PRODUCT_ID = dp.PRODUCT_ID
    GROUP BY
        PRODUCT_ID) m ON b.PRODUCT_ID = m.PRODUCT_ID AND b.CREDITS = m.CREDITS
    JOIN USER u ON b.USER_ID = u.USER_ID
    JOIN Product p ON b.PRODUCT_ID = p.PRODUCT_ID
WHERE
    lower(u.EMAIL) = lower(:APP_USER)));