What is the difference between :=
and =
operators in MySql?
And which place is it stable to use these two?
Is it the same or just an alternative?
The major difference between the == operator and . equals() method is that one is an operator, and the other is the method. Both these == operators and equals() are used to compare objects to mark equality.
The := syntax is shorthand for declaring and initializing a variable, example f := "car" is the short form of var f string = "car"
Variable assignmentThe operator := must be used to give a new value to a variable. A variable must be declared before you can assign a value to it (see declaration of variables above). The type of a variable is identified at declaration time.
Variables defined with ' := ' or ' ::= ' are simply expanded variables; these definitions can contain variable references which will be expanded before the definition is made.
From your other question I know that you mean in the use case of
SELECT variable = column FROM table;
Go ahead and see for yourself...
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;
returns
+------+-------+------------+
| id | @asdf | @asdf = id |
+------+-------+------------+
| 1 | 2 | 0 |
| 2 | 2 | 1 |
| 3 | 2 | 0 |
+------+-------+------------+
In the result a 0
in the last column equals false
, a 1
equals true
.
SELECT @asdf := id FROM foo;
returns
+-------------+
| @asdf := id |
+-------------+
| 1 |
| 2 |
| 3 |
+-------------+
because the value of id
gets assigned to the variable @asdf
If you now issue a
SELECT @asdf;
it returns
+-------+
| @asdf |
+-------+
| 3 |
+-------+
because the row containing 3
was last selected.
SELECT @asdf := id FROM foo ORDER BY id DESC;
returns
+-------------+
| @asdf := id |
+-------------+
| 3 |
| 2 |
| 1 |
+-------------+
Now
SELECT @asdf;
returns
+-------+
| @asdf |
+-------+
| 1 |
+-------+
Difference is clear now?
In a SET
statement, both :=
and =
are assignment operators.
In a SELECT
statement, :=
is an assignment operator and =
is an equality operator.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With