2016-08-16 21 views
0

我正在構建一個拍賣系統。而且我正在處理將顯示用戶擁有的每個出價交易。在我的表格視圖中,我想顯示某個出價交易是否是最高出價,並且我想確定出價是否高於用戶出價。如何在使用MySQL的查詢中創建條件

這裏是我的查詢:

SELECT 
pb.id AS bid_id, 
pb.product_id AS product_id, 
pb.bidding_date AS bidding_date, 
MAX(bidding_price) AS bidding_price 
FROM auction_product_bidding AS pb 
LEFT JOIN auction_product AS p 
ON(pb.product_id = p.id) 
WHERE pb.user_id = 1 
AND p.datetime_end > NOW() 
AND p.`status` = 0 
GROUP BY pb.product_id; 

在此查詢,我可以得到某個用戶的最後競價。

+--------+------------+---------------------+---------------+ 
| bid_id | product_id | bidding_date  | bidding_price | 
+--------+------------+---------------------+---------------+ 
|  55 |   4 | 2016-08-01 11:50:51 |  118000.00 | 
|  74 |   13 | 2016-08-11 14:14:25 |  202.00 | 
+--------+------------+---------------------+---------------+ 

我想添加另一列旁邊的競標價格,以確定是否有更高的出價。

如果用戶有我想補充像「第一名」一個狀態最高的出價,如果有一個更更高的出價,它會顯示「投標再次」

是它在查詢中可能嗎?我讀了控制流程,但我不知道我是否可以使用它。如果不可能的話,也許我會在PHP方面做到這一點。

這就是我希望你能幫助我。

+1

您的查詢不正確或無意義。每個用戶只能出價一次(product_id),但是您不需要在bidding_price上使用MAX,或者用戶可以進行多次出價,但是您只顯示用戶的出價('bid_id', 'bidding_date')任意選擇。 –

+0

BTW:你爲什麼在這裏使用左連接?這是沒有意義的。並且在你的where子句中比較結束時間和狀態,無論如何都只是將它作爲一個內部連接(因爲這些條件會消除任何外部連接的行)。 –

回答

2

用戶的投標:

select * 
from auction_product_bidding 
where user_id = 1 

最新拍賣會:

select * 
from auction_product 
where datetime_end > now() 
and status = 0 

最高出價:

select * 
from auction_product_bidding 
where (product_id, bidding_price) in 
(
    select product_id, max(bidding_price) as max_price 
    from auction_product_bidding 
    group by product_id 
) 

三者結合:

select 
    p.product_name, 
    usrpb.id as bid_id, 
    usrpb.product_id as product_id, 
    usrpb.bidding_date as user_bidding_date, 
    usrpb.bidding_price as user_bidding_price, 
    max(usrpb.bidding_price) as user_bidding_price, 
    maxpb.bidding_price as max_bidding_price, 
    maxpb.bidding_price as max_bidding_price, 
    case when usrpb.user_id = maxpb.user_id then 'yes' else 'no' end as user_is_max_bidder 
from auction_product_bidding usrpb 
join auction_product p on p.id = usrpb.product_id 
join 
(
    select * 
    from auction_product_bidding 
    where (product_id, bidding_price) in 
    (
    select product_id, max(bidding_price) as bidding_price 
    from auction_product_bidding 
    group by product_id 
) 
) maxpb on maxpb.product_id = usrpb.product_id 
where usrpb.user_id = 1 
and p.datetime_end > now() 
and p.status = 0; 
+0

感謝您的幫助。但是有一個錯誤。當我有2個競標項目時,我是最高的,它只顯示1個記錄。 :( – Jerielle