Using a variable in a WHERE clause makes the query take forever

I am facing the problem of using a variable in the WHERE

mysql query clause . I tried searching google but couldn't find an answer.

At the beginning of the MySQL script, I assign some value to a variable and then use that variable in several places within the query. In one particular subquery, if I use a variable, the query keeps running, but if I use a constant value of the variable instead, the query runs after a second.

Please take a look at the example below. Here I am using variable @maxid

in WHERE

sentence

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')

      

This code keeps working and I have to cancel the request. Now consider the below query. This is the same query, but here I am using the constant value of the variable instead of a variable. I replaced the variable @maxid2

with my value '1001-a'

in the script:

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')

      

So my question is, can a variable possibly be executed from a script that it keeps running, but the value of the variable gives the result per second?

Please let me know if I need to explain this more. I have tried many solutions and also searched google but could not find an answer to this question.

+3


source to share


1 answer


Try assigning a value in your query:

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

      



This way my MariaDB can use the index on the column "aCol"

-1


source







All Articles