What does the := operator mean in mysql?

十年热恋 提交于 2019-11-29 02:24:22

问题


I have a mysql table (scho_id,school_name,school_views).

I was looking for a mysql query to get rank of schools on the basis of school_views.

I found this solution on stackoverflow.

SET @points := -1, @num := 0;
SELECT scho_id
, school_views
, @num := if(@points = school_views, @num, @num + 1) as school_rank
, @points := school_info.school_views as dummy
FROM school_info
ORDER BY school_views desc, scho_id asc;

This solved my problem but I notice a new operator := in this query. I am curious to know the meaning and uses of this operator.


回答1:


In MySQL, := is an assignment operator:

SELECT @foo := 'bar';    // variable 'foo' now has value 'bar'
return value: 'bar'

while = is an equality test:

SELECT @foo = 'hi mom'; // does variable 'foo' have the value 'hi mom';
return value: false   ('bar' == 'hi mom' -> false)

Note that you CAN do both equality testing AND assignment with set queries:

SET @foo = 'bar' = 'baz';

which will cause @foo to be assigned false, the boolean result of 'bar' = 'baz'. It executes as the following:

SET @foo = ('bar' = 'baz');
SET @foo = false;


来源:https://stackoverflow.com/questions/39379659/what-does-the-operator-mean-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!