3

Here's the scenario:

When the customer first place his/her order, the table is empty; looks like this

+----+------+---------+
| no | item | results |
+----+------+---------+

When the order has been placed, the table looks like this

+----+--------+---------+
| no | item   | results |
+----+--------+---------+
| 1  | Test 1 | null    |
| 2  | Test 2 | null    |
| 3  | Test 3 | null    |
+----+--------+---------+

That's the easy part. I can use comma separated VALUE clauses in the INSERT query.

The order is then sent to the lab, and when the lab guys are done with the job, the table becomes like this:

+----+--------+---------+
| no | item   | results |
+----+--------+---------+
| 1  | Test 1 | Res 1   |
| 2  | Test 2 | Res 2   |
| 3  | Test 3 | Res 3   |
+----+--------+---------+

This is where your answers come in. I need to update the tests with the results. However I'd really prefer not to do dozens of UPDATE--SET--WHERE statements, one for each test items. Is there any other way?

4

4 回答 4

3

根据存储引擎限制等,您可以在重复时使用插入

http://dev.mysql.com/doc/refman/5.1/en/insert-on-duplicate.html

如果行已经存在,这允许您使用更新值的插入查询。

就像是

insert into table (no, item, result) values(1, "A", "B") on duplicate key update item=values(item), result=values(result)

还有REPLACE INTO

http://dev.mysql.com/doc/refman/5.0/en/replace.html

其中之一应该适合您的需要。

于 2013-04-23T11:29:56.823 回答
1

您可以在其中创建另一个表和INSERT值:

+----+---------+
| no | results |
+----+---------+
| 1  | Res 1   |
| 2  | Res 2   |
| 3  | Res 3   |
+----+---------+

然后只有一个更新:

UPDATE
    t1
SET
    results = t2.results
INNER JOIN
    t2
ON t1.no = t2.no
于 2013-04-23T11:18:21.040 回答
1
INSERT INTO ... ON DUPLICATE KEY UPDATE

表必须有唯一键。它比单行更新更快。

于 2013-04-23T11:28:58.043 回答
0

不幸的是(据我所知),您不能在单个 SQL 查询中执行多个唯一更新。

您可以在单个查询中更新多行,但它们将分别获得相同的更新。

每个更新都需要作为自己的声明来完成。

您最好的选择是编写一个更新单行的循环,并让它为需要完成的每个更新运行。

于 2013-04-23T11:13:21.503 回答