I have this table:
id name bid
1 Test1 5.50
2 Test2 5.50
3 Test3 5.49
I want to select the row with the highest bid. If the highest bid is equal on another row, then it should randomly select one of the highest bid rows.
I tried:
SELECT name,max(bid) FROM table ORDER BY rand()
The output:
id name bid
1 Test1 5.50
My problem is that id “2” is never displayed because for some reason my query is only selecting id “1”
SELECTing
nameandMAX(bid)in the same query makes no sense: you are asking for the highest bid aggregated across all the rows, plus a name that’s not aggregated, so it’s not at all clear which row’s name you’ll be picking. MySQL typically picks the “right” answer you meant (one of the rows that owned the maximum bid) but it’s not guaranteed, fails in all other databases, and is invalid in ANSI SQL.To get a highest-bid row, order by bid and pick only the first result. If you want to ensure you get a random highest-bid row rather than just an arbitrary one, add a random factor to the order clause: