您可以使用臨時變量:
select
@status1 := (case
when user.id < 500 then 'awesome'
else 'lame'
end) as `status`,
(case
when @status1 = 'awesome' then 'You rock'
else 'You stink'
end) as message
from
user;
有些事情你必須瞭解的臨時變量:
- 他們總是通過
@
- 避免之前使用被保留文字,以防萬一(這就是我命名變量的原因
- 的
@
符號後,必須以字母開頭,並且一定不能有空格
- 當您在一個查詢更新,它們將被更新「左到右」(談欄目)和「倒數第一」(談論行)。這可以幫助您計算累計總和或平均值。
舉例(2點):
select @t := 1, @t := @t + 1;
@t1 | @t2
----+----
1 | 2
舉例(3點):
select myTable.x, @t := @t + myTable.x as cummulative_x
from
(select @t := 0) as init, -- You need to initialize the variable,
-- otherwise the results of the evaluation will be NULL
myTable
order by myTable.x -- Always specify how to order the rows,
-- or the cummulative values will be quite odd
-- (and maybe not what you want)
;
x | cummulative_x
---+---------------
1 | 1
1 | 2
2 | 4
3 | 7
臨時變量可以幫助你做一些真棒事...隨意玩耍;如果你想在這個查詢的結果定義條件)
更新
,有兩種方法可以做到這一點:
- 使用上述查詢作爲第二個查詢的數據源(即,使其成爲另一查詢的
from
子句中的子查詢
- 創建臨時表和查詢就可以了
選項1:
select a.*
from (
-- The query with temp variables defined
)
where -- ATTENTION: you need to write the references to the column names of the subquery
選項2:(我個人最喜歡的)
drop table if exists temp_my_temp_table;
create temporary table temp_my_temp_table
select
@status1 := (case
when user.id < 500 then 'awesome'
else 'lame'
end) as `status`,
(case
when @status1 = 'awesome' then 'You rock'
else 'You stink'
end) as message
from
user;
-- Add all appropriate indexes to this newly created table:
-- alter table temp_my_temp_table
-- add index idx_status(`status`),
-- add index idx_mess(message);
-- Make your queries on this new temp table
select * from temp_my_temp_table
-- where ...
;
事情你必須瞭解一個臨時表:
- 他們是在RAM中創建(默認情況下,只有當該表是不是太大)
- 他們只是看到創建它
- 他們被淘汰,一旦創建它關閉時,連接的連接(或終止以任何方式)
- 您不能在
FROM
子句中多次使用它。除此之外,你可以在你的數據庫
另一個更新
只是偶然我碰到this question and its answer來使用它作爲任何其他表。如果你想用你列的結果作爲條件(含臨時變量計算),MySQL允許這樣的:
select
@status1 := (case
when user.id < 500 then 'awesome'
else 'lame'
end) as `status`,
(case
when @status1 = 'awesome' then 'You rock'
else 'You stink'
end) as message
from
user
having
`status` = 'awesome';
而不是使用where
使用having
,而不是指臨時變量,但到別名的列。
我不認爲你可以做到這一點,至少有一個子查詢。我不認爲這會導致任何性能問題:) –
@RodrigoAssis它可以做到(檢查下面的答案;)) – Barranka
好!每天學習 –