Syntax error with “Rand()” function in MySQL in Delphi

依然范特西╮ 提交于 2019-12-31 04:59:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!