puks1978
puks1978

Reputation: 3697

MySql query to find lowest high

I have a table with data:

BID     USER    RETRACTED
1500    75      0
1900    75      0
2000    75      0
2000    75      0
2500    586     0
2750    75      0
3000    75      0
3250    1010    0
3500    75      0
3750    1010    0
4000    75      0

This is a bidding platform but the problem I am struggling with is that users are able to retract their bids. If they do then the information in the DB needs to be amended. Bids are placed in increments.

Currently I have that if USER 1010 retracts their bid, the highest bid is still 4000 when I actually need it to be 2750 because that is the highest value between 2 USERS.

Upvotes: 1

Views: 74

Answers (1)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324760

This would be easiest in parts:

  1. First, delete the bids belonging to the retracted user.
  2. Then, select the user ID of the highest bidder.
  3. Next, find the highest bid that was not made by the highest bidder.
  4. Get the lowest bid higher than the one found in step 3. This will be the new high bid.
  5. Finally, delete all but one of the high bids.

Something like this:

DELETE FROM bids WHERE user=1010;
SET @highbidder=(SELECT user FROM bids ORDER BY bid DESC LIMIT 1;
SET @secondbid=(SELECT bid FROM bids WHERE user != @highbidder ORDER BY bid DESC LIMIT 1);
SET @newhigh=(SELECT bid FROM bids WHERE bid > @secondbid ORDER BY bid ASC LIMIT 1)
DELETE FROM bids WHERE bid > @newhigh;

The three SET statements could be condensed:

SET @newhigh=(SELECT bid FROM bids WHERE bid > (SELECT bid FROM bids WHERE user != (SELECT user FROM bids ORDER BY bid DESC LIMIT 1) ORDER BY bid DESC LIMIT 1) ORDER BY bid ASC LIMIT 1);

However I don't think that's a good idea, partly for performance reasons but mostly for readability.

Upvotes: 2

Related Questions