有什么区别:=和= mysql赋值运算符

Nis*_*sar 14 mysql

有什么区别:MySql中的=和=赋值运算符?

使用这两个地方哪个地方稳定?

它是相同的还是仅仅是另一种选择?

fan*_*nts 18

从你的另一个问题我知道你的意思是在用例中

SELECT variable = column FROM table;
Run Code Online (Sandbox Code Playgroud)

来吧,亲眼看看......

CREATE TABLE foo (id int);
INSERT INTO foo VALUES (1), (2), (3);

SET @asdf = 2; 
SET @asdf := 2; /*those are the same*/
/*As SET is always an assignment operation, it doesn't matter here if you write it with := or with =*/
SELECT id, @asdf, @asdf = id FROM foo;
Run Code Online (Sandbox Code Playgroud)

回报

+------+-------+------------+
| id   | @asdf | @asdf = id |
+------+-------+------------+
|    1 |     2 |          0 |
|    2 |     2 |          1 |
|    3 |     2 |          0 |
+------+-------+------------+
Run Code Online (Sandbox Code Playgroud)

在结果0中,最后一列中的a等于false,1等于true.

SELECT @asdf := id FROM foo;
Run Code Online (Sandbox Code Playgroud)

回报

+-------------+
| @asdf := id |
+-------------+
|           1 |
|           2 |
|           3 |
+-------------+
Run Code Online (Sandbox Code Playgroud)

因为要id赋值给变量@asdf

如果你现在发出一个

SELECT @asdf;
Run Code Online (Sandbox Code Playgroud)

它返回

+-------+
| @asdf |
+-------+
|     3 |
+-------+
Run Code Online (Sandbox Code Playgroud)

因为3最后选择了包含的行.

SELECT @asdf := id FROM foo ORDER BY id DESC;
Run Code Online (Sandbox Code Playgroud)

回报

+-------------+
| @asdf := id |
+-------------+
|           3 |
|           2 |
|           1 |
+-------------+
Run Code Online (Sandbox Code Playgroud)

现在

SELECT @asdf;
Run Code Online (Sandbox Code Playgroud)

回报

+-------+
| @asdf |
+-------+
|     1 |
+-------+
Run Code Online (Sandbox Code Playgroud)

差异很明显了吗?


Mik*_*ike 8

回答

在一条SET语句中,:==均为赋值运算符。

在一条SELECT语句中,:=是赋值运算符,=是相等运算符。

SET @a = 1, @b := 2;
SELECT @a, @b;   -- 1, 2
SELECT @a = @b;  -- 0 (false)

SELECT @a := @b; -- 2
SELECT @a, @b;   -- 2, 2
SELECT @a = @b;  -- 1 (true)
Run Code Online (Sandbox Code Playgroud)