簡體   English   中英

MySQL在SELECT子查詢中使用變量

[英]MySQL using variables in SELECT subquery

是否可以在SELECT中使用變量而不先設置SET?

不知何故,“ @ 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

發現一個錯誤。 原因是該變量在定義之前就已使用。 “ @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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM