【问题标题】:Define and use a variable with a subquery?定义和使用带有子查询的变量?
【发布时间】:2015-05-27 22:35:05
【问题描述】:

我通常知道"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 <b>@foo:=</b>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。或者我可以编写两个单独的查询。但是这些并没有回答我的问题,即是否可以在查询和子查询中安全地定义和使用相同的变量。

【问题讨论】:

标签: mysql correlated-subquery mysql-5.5 user-variables


【解决方案1】:

首先,您的查询实际上没有意义,因为date_ 没有聚合函数。你会得到一个任意值。

也就是说,您可以重复子查询,但我不明白为什么需要这样做。只需使用子查询:

select t.col1, t.first_date,
       datediff(date_, first_date),
       count(*)
from (select t.*, (select min(date_) from t where i.col1 = t.col1) as first_date
      from t
      where anothercol in ('long','list', 'of', 'values')
     ) t
group by col1, days_since_first_date;

不过,正如我所提到的,第三列的值是有问题的。

注意:这确实会为实现子查询产生额外的开销。但是,反正有group by,所以数据是被多次读写的。

【讨论】:

  • 重新分组聚合,注意我是在days_since_first_date上分组的,每个col1date_是一一对应的,也是在col1上的。所以分组应该没问题。
  • 我不明白这如何回答这个问题,即在子查询和查询中定义和使用相同的变量是否安全。
猜你喜欢
  • 1970-01-01
  • 2021-06-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多