简体   繁体   English

MySQL:基于select语句的信息更新多个值

[英]MySQL : Update multiple values based on informatin from select statement

I have on table were dates are mixed up, the startDate and endDate columns need to be switched. 我在表上的日期混合在一起,需要切换startDate和endDate列。 I am use to using SQL Server and this could be accomplished using a cursor in SQL Server, but in MySQL you can only use a cursor inside a SP which i do not want 我习惯使用SQL Server,这可以通过使用SQL Server中的游标来完成,但是在MySQL中,您只能在SP内使用游标,而我不希望这样做

The following statement returns all the records that need to be updated 以下语句返回所有需要更新的记录

select * from calendarTable where endDate < startDate;

I have tried the following code but this first sets the startDate to the value of the endDate then the endDate to the new value of the startDate so this ends as both dates being the same and not switched 我已经尝试了以下代码,但是这首先将startDate设置为endDate的值,然后将endDate设置为startDate的新值,因此这将结束,因为两个日期相同且未切换

update calendarTable
set startDate  = endDate,
    endDate = startDate
where startDate > endDate;

Is there a way of doing this in MySQL similar to a cursor in SQL Server or how would you do this in MySQL? 有没有一种方法可以像在SQL Server中的游标一样在MySQL中执行此操作,或者您将如何在MySQL中执行此操作?

MySQL for the most part evaluates assignments in left-to-right order. MySQL在大多数情况下按从左到右的顺序评估赋值。 If you want to swap the values in two fields, you have to use a temp variable to hold one of the values while moving things around: 如果要在两个字段中交换值,则在移动内容时必须使用temp变量来保存值之一:

UPDATE @temp := startDate, startDate = endDate, endDate = @temp

Assignments within a statement take immediate effect, so if you "reuse" a changed field later on in the query, you get the updated value, not the original one: 一条语句中的赋值立即生效,因此,如果稍后您在查询中“重用”一个更改的字段,则会得到更新的值,而不是原始值:

mysql> select * from foo;
+------+
| x    |
+------+
|    1 |
|   10 |
+------+
2 rows in set (0.00 sec)

mysql> update foo set x=x+1, x=x+50;
Query OK, 2 rows affected (0.00 sec)
Rows matched: 2  Changed: 2  Warnings: 0

mysql> select * from foo;
+------+
| x    |
+------+
|   52 |
|   61 |
+------+
2 rows in set (0.00 sec)

if MySQL used the "original" values for the right-hand side, then the final table would've been 51 and 60 , because the values created by the +1 component would've been trashed by the later +10 . 如果MySQL在右侧使用“原始”值,则最终表将是5160 ,因为由+1组件创建的值将被后面的+10破坏。

Instead, you get a "live" value at each usage in the query, so a field's value depends entirely on what you're doing with it inside the query, and where you're using it in the query. 取而代之的是,您在查询中的每种用法中都会获得一个“实时”值,因此,字段的值完全取决于您在查询中对其进行的操作以及在查询中的使用位置。

i managed to do this by using an joining on a select as below 我设法通过在以下选择上使用联接来做到这一点

UPDATE calendarTable as cal, 
(
    select id,startDate,endDate from calendarTable where endDate < startDate
) as temp
SET cal.startDate = temp.endDate, cal.endDate = temp.startDate  WHERE cal.ID = temp.ID;

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

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