检索数据库中具有字母数字键的最后一条记录
我有一个存储视频游戏详细信息的数据库。表名称是 games &它的主键是“gameNo”,它是字母数字(例如G1,G2,G3...等)。我想检索最后输入的游戏号码,以便在输入下一个游戏时生成游戏号码。当我使用时,
this.cmd = new OleDbCommand("SELECT MAX(gameNo) FROM games",this.con.conObj());
我得到不正确的结果。例如,如果有 gameNo 值,例如 G2 & G190,我想检索G190,但我得到了G2。请提供任何帮助,我们将不胜感激。我是一名学生&如果可能的话,一个好的解释也会有很大的帮助。提前致谢。顺便说一句,我正在使用 Visual C#。
I have a database which stores video game details.The table name is games & its primary key is 'gameNo', which is alphanumeric(ex. G1,G2,G3.... etc.). I want to retrieve the last entered game's number in order to generate the game number for the next game, when it is entered. When I use,
this.cmd = new OleDbCommand("SELECT MAX(gameNo) FROM games",this.con.conObj());
i get incorrect results. For example if there are gameNo values like G2 & G190, I want to retrieve G190, instead I get G2. Please any help would be greatly appreciated. I'm a student & if possible a good explanation would be a huge help too. Thanks in advance. By the way i'm using Visual C#.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是将键存储为 varchar 列的结果。
我会将“G”从数字中分离出来,并有两列。如果它始终是“G”,那么您甚至不需要这两列。
此外,您还遇到另一个问题,这是由于使用 SELECT MAX(gameNo) FROM games 来获取最后的游戏编号而引起的。如果该系统是多用户系统,则两个用户可以获得相同的号码。您没有提到您使用哪个数据库,但所有数据库都可以让您安全地获得游戏的唯一 ID。
我会有一个类似的表(这是针对 SQL Server 的,但你会明白的。
然后,当你为游戏创建新行时,数据库将处理给你一个新的 GameID。
This is a consequence of storing the key as a varchar column.
I would separate out the 'G' from the Number and have two columns. If it is always 'G' then you dont even need the two columns.
Also you have another problem which is caused by using the
SELECT MAX(gameNo) FROM games
to get the last game number. If this system is a multi user system then two users could get the same number. You didn't mention which database you where using but all databases will let you safely get a unique id for a game.I would have a table something like (This is for SQL Server but you will get the idea.
Then when you create the new row for the game the database will handle giving you a new GameID.
老实说,虽然肯定有一个解决方案可以解析查询中的gameNo,但我强烈建议更改数据库模型,以使用整数来使用适当的自动递增主键 数据类型。
To be honest, while there is definitely a solution to this that parses the
gameNo
in the query, I'd strongly suggest changing the database model to use a proper auto-incrementing primary key usinginteger
data type instead.这里有几个问题。一是因为 gameNo 是字母数字并不意味着最后记录是最大值。您必须详细说明此列中的值如何自动递增。另一个问题是“最大”是什么。对于字母数字,值将作为测试进行比较,而不是数字。因此,“3”将出现在“1a”之前。
There's a couple of issues here. One is just because gameNo is alphanumeric doesn't mean the last record is the largest value. You'll have to detail how the values in this column are auto-incremented The other issue is what is "largest". With alphanumeric the values are compared as test, not numbers. So, '3' would come before '1a'.