我通常知道"the order of evaluation for expressions involving user variables is undefined",所以我們不能在同一個select
語句中安全地定義和使用變量。但是如果有子查詢呢?舉個例子,我有這樣的事情:定義和使用一個變量與子查詢?
select col1,
(select min(date_)from t where i.col1=col1) as first_date,
datediff(date_, (select min(date_)from t where i.col1=col1)
) as days_since_first_date,
count(*) cnt
from t i
where anothercol in ('long','list','of','values')
group by col1,days_since_first_date;
有沒有辦法使用(select @foo:=min(date_)from t where i.col1=col1)
安全,而不是重複的子查詢?如果是這樣,我可以在datediff
函數中或第一次出現子查詢(或任一個)嗎?
當然,我可以做
select col1,
(select min(date_)from t where i.col1=col1) as first_date,
date_,
count(*) cnt
from t i
where anothercol in ('long','list','of','values')
group by col1,date_;
,然後做一些簡單的後期處理,以獲得datediff
。或者我可以寫兩個單獨的查詢。但是這些不能回答我的問題,即是否可以在查詢和子查詢中安全地定義和使用相同的變量。
此鏈接可能對您有所幫助。 http://stackoverflow.com/questions/16715504/mysql-define-a-variable-within-select-and-use-it-within-the-same-select –