简体   繁体   English

SQL是否存在更新数量

[英]SQL if exist update quantity

What I'm trying to achieve is a single form where user with a handheld barcode reader read the barcode and the page on each read send a SQL command to record the number of product scanned. 我要实现的是一种单一形式,其中使用手持式条形码读取器的用户读取条形码,并且每次读取的页面都会发送一个SQL命令来记录扫描的产品数量。

I have a database named packinglist and a table named list with two columns barcode and quantity. 我有一个名为packinglist的数据库和一个名为list的表,该表具有两列条形码和数量。

I have this string on the page: 我在页面上有这个字符串:

INSERT INTO `gpbeticlm`.`packinglist` (barcode,quantity) VALUES (':field',1) ON DUPLICATE KEY UPDATE quantity=VALUES(quantity);

The first time I read a barcode it is inserted correctly in the database with quantity 1, but the second time I read the same barcode instead of having quantity 2 it doesn't update the database and remain 1, so I try to read another barcode and it doesn't do nothing the database keep 1 row with quantity 1. 第一次读取条形码时,它已正确插入数量为1的数据库中,但是第二次读取相同的条形码而不是数量为2时,它不会更新数据库并保持为1,所以我尝试读取另一个条形码并且它不会做任何事情,数据库保留数量为1的1行。

If the barcode is the primary key of the table, you could use the INSERT...ON DUPLICATE KEY UPDATE construct 如果条形码是表的主键,则可以使用INSERT...ON DUPLICATE KEY UPDATE构造

You can find more information about this construct here 您可以在此处找到有关此构造的更多信息

I'll try to clarify a bit. 我会尝试澄清一下。

You're doing ON DUPLICATE KEY UPDATE quantity=VALUES(quantity); 您正在执行ON DUPLICATE KEY UPDATE quantity=VALUES(quantity); , which takes the inserted value (which is 1 ) as the value to write in the updated field. ,它将插入的值(即1 )作为要写入更新字段中的值。 So this will always be 1 instead of the incremented value. 因此,它将始终为1而不是增量值。

You could rewrite this construct as mentioned in the beforementioned link to something like this 您可以按照前面提到的链接那样重写此构造,例如:

ON DUPLICATE KEY UPDATE quantity=quantity + 1

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

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