我在桌子上的日期混淆了,需要切换startDate和endDate列。我习惯使用SQL Server,这可以使用SQL Server中的游标来完成,但在MySQL中你只能使用我不想要的SP内的游标
以下语句返回需要更新的所有记录
select * from calendarTable where endDate < startDate;
我已经尝试了以下代码,但是这首先将startDate设置为endDate的值,然后将endDate设置为startDate的新值,因此这两个日期相同且未切换
update calendarTable
set startDate = endDate,
endDate = startDate
where startDate > endDate;
有没有办法在MySQL中执行此操作,类似于SQL Server中的游标,或者您将如何在MySQL中执行此操作?
答案 0 :(得分:0)
MySQL大部分都是按照从左到右的顺序评估作业。如果要在两个字段中交换值,则必须使用临时变量来保存其中一个值,同时移动物体:
UPDATE @temp := startDate, startDate = endDate, endDate = @temp
语句中的赋值立即生效,因此如果您稍后在查询中“重复使用”已更改的字段,则会获得更新的值,而不是原始值:
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)
如果MySQL使用右侧的“原始”值,则最终表格将为51
和60
,因为+1
组件创建的值会被后来的+10
摧毁。
相反,您在查询中的每次使用时都会获得“实时”值,因此字段的值完全取决于您在查询中使用它的内容,以及您在查询中使用它的位置。
答案 1 :(得分:0)
我设法通过使用如下的选择加入来实现这一目标
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;