1

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

3 表

Table User
USER_ID
EMAIL

Table Product
PRODUCT_ID
USER_ID

Table Bid
BID_ID
PRODUCT_ID
USER_ID
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 返回当前用户的邮箱地址 (:APP_USER)

真正的问题始于“和”,因为用户过滤工作正常。我不知道如何在子查询中获取比较的(当前)PRODUCT_ID。我很确定如果我在子查询结束时获得该值,它将起作用。

使用 Oracle 数据库。

任何帮助表示赞赏:)

4

2 回答 2

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))
于 2013-01-04T15:16:58.440 回答
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)));
于 2013-01-04T15:24:53.950 回答