Forum Moderators: open

Message Too Old, No Replies

MySQL GROUP BY problem

         

scim1971

1:26 pm on Jul 24, 2009 (gmt 0)

10+ Year Member



Hi,

I'm using MySQL with ASP pages. I'm building an auction style site and I want to show a member a list of their active bids. Because then can bid more than once for an "lot" I only want to show their highest bid for each "lot" - so, for instance if the bid (for one LOT) £50, then £75.00, then £100.00 it would only show the £100.00 bid.

The member can bid on many different "lots" so the list I want will show the "sale name", the sale "closing date", the "LOT number", their "bid", their "bid date" and a status message about whether they're the highest bidder or not.

My problem is that I can easily build the list to show "ALL" their bids and sort/order that list but it will include all the bods they've made for a particular "LOT" not just their highest bid.

I tried using DISTINCT on the bidlotId (the unique identifier for each lot in the bids table) but that didn't make any difference.

I then tried using GROUP BY bidlotId which does only show one bid for each lot but unfornately it's not the highest bid.

I need to figure out how to order/sort the GROUP BY function to show the highest bid for each lot.

This is my SQL:

"SELECT bidId, bidlotId, bidvalue, biddatetime, saleId, salename, saleclosingdate, lotnum, lotreserve
FROM dbname.tblbids, dbname.tblsales, dbname.tbllots
WHERE bidcustId = ? AND bidsaleId = saleId AND saleclosingdate > Now() AND bidlotId = lotId
GROUP BY bidlotId
ORDER BY saleclosingdate ASC, bidvalue DESC"

Can any one help?

Many thanks in advance.

SteveWh

4:43 am on Jul 26, 2009 (gmt 0)

10+ Year Member



I'm only just learning MySQL myself, but I believe the keyword you're looking for may be "LIMIT".

scim1971

8:55 am on Jul 26, 2009 (gmt 0)

10+ Year Member



Hi,

For those of you with a similiar problem a clever guru from another post came up with this solution:

SELECT B.bidId
, B.bidlotId
, B.bidvalue
, B.biddatetime
, S.saleId
, S.salename
, S.saleclosingdate
, L.lotnum
, L.lotreserve
FROM ( SELECT bidlotId
, MAX(bidvalue) AS maxvalue
FROM tblbids
WHERE bidcustId = ?
GROUP
BY bidlotId ) AS M
INNER
JOIN tblbids AS B
ON B.bidlotId = M.bidlotId
AND B.bidvalue = M.maxvalue
INNER
JOIN tbllots AS L
ON L.lotId = B.bidlotId
INNER
JOIN tblsales AS S
ON S.saleId = B.bidsaleId
AND S.saleclosingdate > Now()
ORDER
BY S.saleclosingdate ASC
, B.bidvalue DESC

SteveWh

9:28 am on Jul 26, 2009 (gmt 0)

10+ Year Member



Yes, I ran across that post later. Complicated!

lionheart620

4:53 pm on Aug 12, 2009 (gmt 0)

10+ Year Member



Alternatively you can try the solution posted here:
[tjbourke.com...]
Though I didn't go through your solution thoroughly, it does appear to be more efficient. However, for someone else, this post might be useful.