简体   繁体   English

多行更新的语法,用于更新具有唯一信息的特定行

[英]Syntax of a multi-row update that updates specific rows with unique information

I've been having a hard time finding a good example of exactly what I am trying to do. 我一直很难找到一个很好的例子来说明我正在尝试做什么。

I have a multidimensional array containing 1-N entries. 我有一个包含1-N条目的多维数组。 I want to update a table in MySQL from this array, but I want to update all the rows in a single query. 我想从这个数组更新MySQL中的表,但我想更新单个查询中的所有行。 I wasn't able to find any examples of a multi-row update that set the values for multiple columns and also had where clause like functionality to determine which rows were updated. 我无法找到任何多行更新的示例,这些更新设置了多列的值,并且还具有where子句,类似于确定哪些行已更新的功能。

The table I am working with is setup like this: 我正在使用的表是这样设置的:

TABLE
name varchar,
quota int,
warehouse int,
production int,
missing int

The array is ordered like this, TABLE.name corresponds to Material Name: 数组的排序方式如下,TABLE.name对应于材质名称:

$list = array(
    'Material Name One'=>array(1000,200,600,200),
    'Material Name Two'=>array(5000,0,4500,500)
);

Could someone please provide an example of how to form this type of syntax? 有人可以提供一个如何形成这种语法的例子吗?

I want to use a single update as the size of the array/table may eventually grow quite large and I'm under the impression that this method is better than making hundreds of small updates in quick succession. 我想使用单个更新,因为数组/表的大小最终可能会变得非常大,我的印象是这种方法比快速连续制作数百个小更新要好。

First of all I don't see what is wrong with separately executed updates especially with prepared statements. 首先,我没有看到单独执行的更新有什么问题,尤其是使用预准备语句。

But if you want for any reason to implement a multi row update you will need to build a query like this 但是如果你想以任何理由实现多行更新,你需要构建一个这样的查询

UPDATE Table1 t JOIN
(
    SELECT 'Material Name One' name, 1000 quota, 200 warehouse, 600 production, 200 missing
    UNION ALL
    SELECT 'Material Name Two', 5000, 0, 4500, 500
    -- You can add extra rows here
    -- with UNION ALL
) u ON t.name = u.name
   SET t.quota = u.quota,
       t.warehouse = u.warehouse,
       t.production = u.production,
       t.missing = u.missing;

Here is SQLFiddle example. 这是SQLFiddle的例子。

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

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