在MYSQL中的列之间移动值(?)

时间:2016-12-20 16:36:37

标签: mysql

我试图在它们之间移动3个不同列的值,但我无法使其正常工作

<?php

include_once 'db_connect.php';
include_once 'psl-config.php';
include_once 'db_manual_connect.php';


$error_msg = "";
if (isset($_POST['value'], $_POST['id'])) {
$value= $_POST['value'];
$id = $_POST['id'];

    if (!$conn) {
         die("Connection failed: " . mysqli_connect_error());
    }
    $sql = "UPDATE equipo SET 
    slot1= CASE WHEN slot1= '".$value."' THEN slot1
                    WHEN slot2= '".$value."' THEN slot2
                    WHEN slot3= '".$value."' THEN slot3 END,

    slot2= CASE WHEN slot1= '".$value."' THEN slot2
                    WHEN slot2= '".$value."' THEN slot1
                    WHEN slot3 = '".$value."' THEN slot2 END,

    pokemon3 = CASE WHEN slot1= '".$value."' THEN slot3
                    WHEN slot2= '".$value."' THEN slot3
                    WHEN slot3= '".$value."' THEN slot1 END WHERE id = '".$id."'";

    $result = mysqli_query($conn, $sql);

1 个答案:

答案 0 :(得分:0)

您可以使用此类查询执行此操作。首先,您必须将slot1-3中的值保存在局部变量中,然后您可以测试和设置字段。

mysql> SELECT * from theTable;
+----+-------+-------+
| id | slot1 | slot2 |
+----+-------+-------+
|  1 |     3 |     6 |
|  1 |     6 |    12 |
|  1 |     8 |    16 |
|  2 |     5 |    10 |
|  2 |     7 |    14 |
+----+-------+-------+
5 rows in set (0,00 sec)

mysql> update  theTable t
    -> CROSS join ( SELECT @tmp_slot1:=0, @tmp_slot2:=0) AS init
    -> set
    ->     slot1 = @tmp_slot1 := slot1,
    ->     slot2 = @tmp_slot2 := slot2,
    ->     slot1 = @tmp_slot2,
    ->     slot2 = @tmp_slot1;
Query OK, 5 rows affected (0,00 sec)
Rows matched: 5  Changed: 5  Warnings: 0

mysql> SELECT * from theTable;
+----+-------+-------+
| id | slot1 | slot2 |
+----+-------+-------+
|  1 |     6 |     3 |
|  1 |    12 |     6 |
|  1 |    16 |     8 |
|  2 |    10 |     5 |
|  2 |    14 |     7 |
+----+-------+-------+
5 rows in set (0,00 sec)

mysql>

如果它对您有用,请告诉我。经过测试

包含2个字段的示例

{{1}}