简体   繁体   English

如何编写这样的MySQL语句?

[英]How to write such a MySQL statement?

create table test(
  id ...
  weight ..
);

How to write such a statement so that the weight of each record is at least the weight of previous record plus 1? 如何编写这样一条语句,使每条记录的权重至少为先前记录的权重加1?

recordN.weight >=(recordN-1).weight+1

you need to check it before inserting in to table, eg you can get the last row from the table with query 您需要在插入表之前对其进行检查,例如,您可以通过查询从表中获取最后一行

select weight from test where id = (select MAX(id) from test);

then compare this weight value from the values you are inserting and 然后从您要插入的值中比较该重量值,然后

if (newWeight >= weight)
{
   //insert here
}

One of the ways is to store the weight in a variable and then use it in an update statement 一种方法是将权重存储在变量中,然后在更新语句中使用它

SELECT weight FROM test ORDER BY id DESC LIMIT 1 INTO @weight;
INSERT INTO test (weight) VALUES (@weight+1);

That will get the weight of the previous record and use it in the next insert statement (assuming you have auto increment ids). 这将获得上一条记录的权重,并在下一条插入语句中使用它(假设您具有自动增量ID)。

You can also concatenate the query: 您还可以串联查询:

INSERT INTO test (weight) SELECT (weight+1) FROM test ORDER BY id DESC LIMIT 1;

Sounds strange. 听起来很奇怪。 Are you updating existing data, adding a new row to the table or selecting the data sorted by weight? 您是要更新现有数据,向表中添加新行还是选择按权重排序的数据?

Sorting is easiest, use SELECT ... ORDER BY weight; 排序最简单,使用SELECT ... ORDER BY weight;

Adding a row, you could use the previous answer: INSERT INTO test (weight) (SELECT (max(weight)+1) FROM test); 添加一行,您可以使用上一个答案:INSERT INTO test(weight)(SELECT(max(weight)+1)FROM test);

Although note that (1) There is an autoincrement function in MySQL if that's what you're looking for; 尽管注意(1)如果您要查找的是MySQL中的一个自动递增函数; (2) in good DB tables, row order is immaterial; (2)在好的数据库表中,行顺序无关紧要; rows can be sorted without information being lost. 可以对行进行排序而不会丢失信息。 If you are relying on row order for anything, consider your database design again. 如果您要依靠行顺序执行任何操作,请再次考虑数据库设计。

Finally, if you're trying to update the data, adding to the weight, it's a common problem. 最后,如果您尝试更新数据,增加权重,这是一个常见问题。 I always have to look it up online, so I'll leave you to do that :) 我总是必须在线查找它,所以我会让你这样做:)

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

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