我的MySQL语句中有一个sub select语句,它只是拒绝知道顶级表/列引用是什么。
这是我第一次使用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 :(得分: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 **
原因是,afaik,如果你只在子查询中使用表名(plugin_thold_log),那么它总是将它作为这个子查询实例引用。