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

时间:2013-12-11 09:35:27

标签: mysql

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

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

它是相同的还是仅仅是一种替代方案?

2 个答案:

答案 0 :(得分:15)

从您的其他问题我知道您的意思是

的用例
SELECT variable = column FROM table;

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

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;

返回

+------+-------+------------+
| id   | @asdf | @asdf = id |
+------+-------+------------+
|    1 |     2 |          0 |
|    2 |     2 |          1 |
|    3 |     2 |          0 |
+------+-------+------------+

在结果中,最后一列中的0等于false1等于true

SELECT @asdf := id FROM foo;

返回

+-------------+
| @asdf := id |
+-------------+
|           1 |
|           2 |
|           3 |
+-------------+

因为id的值已分配给变量@asdf

如果您现在发出

SELECT @asdf;

它返回

+-------+
| @asdf |
+-------+
|     3 |
+-------+

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

SELECT @asdf := id FROM foo ORDER BY id DESC;

返回

+-------------+
| @asdf := id |
+-------------+
|           3 |
|           2 |
|           1 |
+-------------+

现在

SELECT @asdf;

返回

+-------+
| @asdf |
+-------+
|     1 |
+-------+

现在差异很明显了吗?

答案 1 :(得分:4)

答案

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)