问题
I am trying to use the Rand() function within MySQL to select a random record but I am getting a syntax error in the Rand() LIMIT line
qryCards.SQL.Add('SELECT * FROM tblCards WHERE Card_Rarity = "Epic"');
qryCards.Open;
iCount := qryCards.RecordCount;
qryCards.Close;
qryCards.SQL.Clear;
qryCards.SQL.Add('SELECT * FROM tblCards ORDER BY rand(' + IntToStr(iCount) + ') LIMIT 1');
qryCards.Open;
ShowMessage(qryCards.FieldByName('Card_Name').AsString);
回答1:
First off, you are not using RAND() correctly. It returns a decimal number 0 <= N < 1. The input value is a seed, not an upper limit like you are expecting. To get a random integer number between 0 <= N < Count, you have to multiple the result, ie RAND()*Count, which you are not doing. But you don't need to do that, you can just use RAND() by itself, there is no need to query the record count first:
qryCards.SQL.Text := 'SELECT * FROM tblCards WHERE Card_Rarity = "Epic" ORDER BY RAND() LIMIT 1';
qryCards.Open;
ShowMessage(qryCards.FieldByName('Card_Name').AsString);
Otherwise, you can select a random record by specifying an offset to the LIMIT clause, eg:
qryCards.SQL.Text := 'SELECT * FROM tblCards WHERE Card_Rarity = "Epic"';
qryCards.Open;
iCount := qryCards.RecordCount;
qryCards.Close;
qryCards.SQL.Text := 'SELECT * FROM tblCards WHERE Card_Rarity = "Epic" LIMIT ' + IntToStr(Random(iCount)) + ', 1');
qryCards.Open;
ShowMessage(qryCards.FieldByName('Card_Name').AsString);
If your table has an auto-increment id field with no gaps in it, there are other techniques you can use RAND() with. See MySQL Select Random Records for examples.
来源:https://stackoverflow.com/questions/58062201/syntax-error-with-rand-function-in-mysql-in-delphi