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

戏子无情 提交于 2019-12-02 04:30:02

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.

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