2014-03-07 80 views
0

在沒有SET之前的SELECT中可以使用變量嗎?在SELECT子查詢中使用變量的MySQL

不知何故'@period'變量不總是正常工作。例如,在MySQL Workbench(v5.2)中,只有在第二次調用後纔會顯示結果,如果變量發生更改,結果將僅在第二次運行時正確。 phpMyAdmin的顯示正確的行數,但沒有任何條目,可有人請解釋什麼是錯在以這樣的方式使用變量:

select sql_no_cache @num := @num + 1 as `#`, l.* from (

    select s.* from (
    select 
    @num := 0 as 'Label 1', 
    @period := 31 as 'LAbel 2', 
    '' as 'Label 3' 

    union 

    select concat(users.first_name, ' ',users.last_name),u.type, u.date, u.description from (

    select c.user_id as uguid, 'type1' as type, c.date_start as date, c.description from table1 c 
    where deleted = 0 
    and date_start > SUBDATE(CURRENT_DATE,@period) 

    union 
    ... 
) as u) as l 

回答

0

發現一個錯誤。 原因是變量在定義之前使用。 '@period'在查詢中定義,但是它首先在首先執行的子查詢中使用。 因此,解決方案是將變量定義與子查詢所在的同一級別。

喜歡的東西:

select sql_no_cache @num := @num + 1 as `#`, l.* from (

     select s.* from (
     select 
     @num := 0 as 'Label 1', 
     '' as 'LAbel 2', 
     '' as 'Label 3' 

     union 

     select concat(users.first_name, ' ',users.last_name),u.type, u.date, u.description from  (
      select o2.* from 
      (select @period:=31) as o1 
      join (
       select c.user_id as uguid, 'type1' as type, c.date_start as date, c.description from table1 c 
       where deleted = 0 
       and date_start > SUBDATE(CURRENT_DATE,@period) 

       union 
       ... 
      ) as o2 
     ) as u 
    ) as l