mysql - 在 SELECT 语句中设置变量 mysql

标签 mysql

您好,我想知道是否可以假设 SELECT 语句从左到右选择字段,以确保构建一个安全的语句如下(尝试使用尚未设置的变量是不好的):

SELECT @variable := IFNULL(var, 0), value + @variable, somevalue, value2*@variable, ..., @variable/whatever...

FROM table1 LEFT JOIN table2 LEFT JOIN table3

我问这个问题的原因是因为由于使用了 LEFT JOINS,某些元组中的 var 可能等于 null(假设 var 来自表 3),并且我需要使用该变量如您所见,多次创建衍生字段,因此我不想每次都使用 IFNULL(var, 0)。

最佳答案

来自the docs (强调):

As a general rule, other than in SET statements, you should never assign a value to a user variable and read the value within the same statement. For example, to increment a variable, this is okay:

SET @a = @a + 1;

For other statements, such as SELECT, you might get the results you expect, but this is not guaranteed. In the following statement, you might think that MySQL will evaluate @a first and then do an assignment second:

SELECT @a, @a:=@a+1, ...;

However, the order of evaluation for expressions involving user variables is undefined.

因此,如果我们照章办事,那么您问题的答案就是

关于mysql - 在 SELECT 语句中设置变量 mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28803551/

相关文章:

php - 使用 PHP 通过表单向 MySQL 添加多行

php - Yii 中的 AR 添加重复行

mysql - 从 MySQL 中的文本列表创建表

mysql - 迁移到 Google SQL 时 Change master 失败

php - 内连接太慢。怎么才能更快

MySQL用单个查询反转一列

php - 无法通过PHP连接到docker mysql容器

java - 将 uuid(UUID 类型)插入 mysql 时报告键 PRIMARY 的重复条目

php - 使用不同的值多次搜索数据库表

php - 如何在单个 while 循环中从多个查询中检索值?