简体   繁体   English

MySQL的插入和更新表最大3

[英]mysql insert and update table with max 3

I have a php script that logs inputs from a form into a mysql database table. 我有一个php脚本,它将来自表单的输入记录到mysql数据库表中。 I'm looking for a way to insert this data untill 3 rows are created, after which it has to update the existing rows so that the first one updates to the new input, the second one to the former first input and the third one to the former second input. 我正在寻找一种在创建3行之前插入此数据的方法,此后它必须更新现有行,以便第一个更新为新输入,第二个更新为以前的第一个输入,第三个更新为前一个输入。前第二个输入。

Table: 表:

CREATE TABLE IF NOT EXISTS inputlog (
  id int(11) NOT NULL auto_increment,
  userid int(11) NOT NULL default '0',
  name text,
  value text,
  PRIMARY KEY (id)
 ) ENGINE=MyISAM DEFAULT CHARSET=latin1;`

For the first three rows i use: 对于前三行,我使用:

insert into inputlog (userid,name,value) values('$userid','$name','$value')

After that is has to become: 之后必须成为:

update inputlog set value = '$value' where userid = '$userid' and name = '$name'

where it has to update all the successive rows. 它必须更新所有连续的行。

How can i accomplish this? 我怎样才能做到这一点?

Too long for comments, so... 评论太久,所以...

Looks like you want to have only 3 rows in your table because you want the data to be sorted by the id. 看起来您只希望表中有3行,因为您希望按ID对数据进行排序。 So id=1 will be the latest value, then id=2 and finally id=3. 因此,id = 1将是最新值,然后是id = 2,最后是id = 3。

In short, do not do that, the id field can be any value. 简而言之,不要这样做,id字段可以是任何值。 Do not code for that. 不要为此编写代码。 The danger is if you use the id in another table as a foreign key, you will loose referential integrity. 危险是,如果将另一个表中的id用作外键,则会失去参照完整性。 What I propose is: 我建议的是:

  • Add an timestamp column for each row. 为每一行添加一个时间戳列。
  • Every time you insert a new value, set the timestamp column to NOW() 每次插入新值时,将timestamp列设置为NOW()
  • When selecting, sort on the timestamp and limit to 3 results 选择时,按时间戳排序并限制为3个结果

If you MUST have only 3 rows, you can then delete the row except for the 3 most recent timestamps. 如果您必须只有3行,则可以删除除3个最近的时间戳以外的行。


But... if you must do that... 但是...如果您必须这样做...

  • perform a SELECT with the first 2 lines 用前2行执行SELECT
  • truncate the table (delete all rows) 截断表(删除所有行)
  • insert the new line, then the 2 stored lines 插入新行,然后插入2行

You will then ahve your 3 rows in the order you want. 然后,您将按所需顺序排列3行。 But without seeing the entire reasoning for your application, my "spider sense" tells me you will hit a wall later on... 但是我看不到您的申请的全部理由,我的“蜘蛛意识”告诉我您以后会碰壁...


And check the comments for other things to worry about. 并检查注释中其他需要担心的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM