2013-01-04 71 views
1

我一直在APEX的拍賣網站上工作。對於拍賣網站,我需要做一個概述,說明哪些產品是由某人購買的。肯定它的只是我忘了,但我怎樣才能獲得結果在以下情況:在子查詢中獲取Id

3表

Table User 
USER_ID 
EMAIL 

Table Product 
PRODUCT_ID 
USER_ID 

Table Bid 
BID_ID 
PRODUCT_ID 
USER_ID 
CREDITS 

Ofcourse有更多的列,但我想,讓他們出來,使explenation稍微容易。

最少報名結果

顯示產品從產品表。但只有當前用戶的出價最高(Credits)。

到目前爲止

我一直在想/想在這一個了很多,但在子查詢結束不斷收到死亡。 (:APP_USER)

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

真正的問題在「和」爲用戶過濾工作正常啓動。我不知道如何在子查詢中獲取比較(當前)的PRODUCT_ID。我很確定,如果我在子查詢的末尾得到這個值,它就可以工作。

使用Oracle數據庫。

任何幫助表示讚賞:)

回答

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)) 
+0

工作出色,對於那些檢查出這個問題的人:請注意在第一個代碼部分缺少引號:)感謝您的幫助! –

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))); 
+0

非常感謝回答,而我與其他答案一起去了,我試過這個也是,並發現它工作以及:)感謝您的幫助! –