在WHERE子句中使用变量会导致查询永久持续

时间:2014-09-13 21:38:23

标签: mysql

我在使用mysql查询的WHERE子句中的变量时遇到了问题。我试过搜索谷歌但找不到任何答案。

在MySQL脚本的开头,我将一些值分配给变量,然后在查询内的多个位置使用该变量。在一个特定的子查询中,如果我使用该变量,则查询将继续运行,但如果我使用变量的常量值,则查询将在一秒钟内运行。

请看下面的例子。这里我在@maxid子句

中使用变量WHERE
set @maxid2 = '1001-a';
select distinct
    dc.db_date,
    dc.year_month,
    dc.year,
    dc.week,
    dc.day,
    dc.dayofweek - 1 as DayOfWeek,
    em.ID as EmployeeID,
    concat_ws(' ', em.`FirstName`, `LastName`) as EmployeeName
from
    datavis_cal dc
        cross join
    employees_data em ON em.ID = @maxid2
        and dc.db_date >= (select 
            min(assigndate)
        from
            attendance_data
        where
            ID = @maxid2)
        and db_date <= curdate()
        and em.DeptID = (select distinct
            DeptID
        from
            users
        where
            username = 'demo')

此代码继续运行,我必须取消查询。现在看看下面的查询。它是相同的查询,但在这里而不是变量,我使用变量的常量值。我已在脚本中将变量@maxid2替换为值'1001-a'

set @maxid2 = '1001-a';
select distinct
    dc.db_date,
    dc.year_month,
    dc.year,
    dc.week,
    dc.day,
    dc.dayofweek - 1 as DayOfWeek,
    em.ID as EmployeeID,
    concat_ws(' ', em.`FirstName`, `LastName`) as EmployeeName
from
    datavis_cal dc
        cross join
    employees_data em ON em.ID = '1001-a'
        and dc.db_date >= (select 
            min(assigndate)
        from
            attendance_data
        where
            ID = '1001-a')
        and db_date <= curdate()
        and em.DeptID = (select distinct
            DeptID
        from
            users
        where
            username = 'demo')

所以我的问题是,变量可能对脚本运行了什么,它继续运行但是变量的值会产生第二个结果?

如果我需要解释一下,请告诉我。我尝试了很多解决方案,也搜索了谷歌,但没有找到任何答案。

1 个答案:

答案 0 :(得分:-1)

尝试将值赋值放在查询中:

select aCol
from myTable, (SELECT @value := 2) as a
where aCol = @value;

这样我的MariaDB就可以在列&#39; aCol&#39;

上使用索引