2014-03-13 24 views
3

我在我的MySQL語句中有一個子選擇語句,它只是拒絕瞭解頂級表/列引用是什麼。SubQuery的MySQL參考頂級表

這是第一次我一直在處理MySQL和它似乎(在SQL Server 2008中注意此查詢結構工作得很好)

這裏是引用子查詢中的表和列時,有一定的侷限性我的查詢:

select 
plugin_thold_log.id as id, 
plugin_thold_log.host_id as hostname, 
from_unixtime(plugin_thold_log.time) as time, 
CASE 
    when TIMESTAMPDIFF(MINUTE,(select from_unixtime(a.time) from plugin_thold_log a where a.id <  plugin_thold_log.id and a.time >= '1393603200' and a.time <= '1394121600' order by a.id desc LIMIT 1),from_unixtime(plugin_thold_log.time)) is null then 1 
    when TIMESTAMPDIFF(MINUTE,(select from_unixtime(a.time) from plugin_thold_log a where a.id < plugin_thold_log.id and a.time >= '1393603200' and a.time <= '1394121600' order by a.id desc LIMIT 1),from_unixtime(plugin_thold_log.time)) > 30 then 1 
    when TIMESTAMPDIFF(MINUTE,(select from_unixtime(a.time) from plugin_thold_log a where a.id < plugin_thold_log.id and a.time >= '1393603200' and a.time <= '1394121600' order by a.id desc LIMIT 1),from_unixtime(plugin_thold_log.time)) < 30 
    and TIMESTAMPDIFF(MINUTE,(select from_unixtime(c.time) from (select time from plugin_thold_log b where b.id < id and b.time >= '1393603200' and b.time <= '1394121600' order by b.id desc LIMIT 7) c order by 1 asc LIMIT 1),from_unixtime(plugin_thold_log.time)) < 30 then 0 
    when TIMESTAMPDIFF(MINUTE,(select from_unixtime(a.time) from plugin_thold_log a where a.id < plugin_thold_log.id and a.time >= '1393603200' and a.time <= '1394121600' order by a.id desc LIMIT 1), from_unixtime(plugin_thold_log.time)) < 30 
    and TIMESTAMPDIFF(MINUTE,(select from_unixtime(c.time) from (select time from plugin_thold_log b where b.id < id and b.time >= '1393603200' and b.time <= '1394121600' order by b.id desc LIMIT 7) c order by 1 asc LIMIT 1),from_unixtime(plugin_thold_log.time)) is null then 0 
else 1 end as timebracket 
from plugin_thold_log 
where plugin_thold_log.time >= '1393603200' and plugin_thold_log.time <= '1394121600' 
order by 1 

我不會進入細節什麼的查詢不會(我只想說,它把一個1當它發現一個新的日誌條目然而,當參考TIMESTAMPDIFF函數裏面我的子查詢中plugin_thold_log.id得到一個錯誤,指出plugin_thold_log.id列在where子句中未知。

看起來MySQL在放入二級子查詢時失去了頂級表引用。

任何想法如何解決這個問題?

回答

0

如果我看到和理解對不對

when ** from plugin_thold_log a where a.id < plugin_thold_log.id ** 

那麼第二plugin_thold_log應該引用其他表?在這種情況下,你應該給它一個別名:

select 
plugin_thold_log.id as id, 
plugin_thold_log.host_id as hostname, 
** 
from plugin_thold_log p 
where ** 
order by 1 

,然後用它在你的子查詢:

when ** from plugin_thold_log a where a.id < p.id ** 

原因是,據我所知,如果你只在使用表名(plugin_thold_log)子查詢,那麼它將始終引用它作爲此子查詢實例。

+0

謝謝您的評論..但我也試過這個,它仍然不保留對第一級表的引用。這適用於第二級查詢,但是當我回到第三級查詢時,它無法找到頂級表引用。 –