无法理解mysql查询

时间:2013-05-17 16:58:27

标签: mysql optimization

昨天我有一个问题是关于用rand()命令mysql查询。我在这里得到了一个很好的答案: https://stackoverflow.com/a/16597706/2333744

答案的代码如下。

create temporary table results as
(Select *, @rn := @rn + 1 as rn, rand() as therand
from table1 inner join
  table2
  on table1.in = table2.in cross join
    (select @rn := 0) const
where table1.T = A
);

select *
from results
where therand < 1000/@rn
order by therand
limit 500;

我理解除了

之外的一切
cross join (select @rn : = 0) const

我不确定这是做什么以及它是否重要。当我删除它时,我没有改变性能。任何人都可以理解这部分吗?

2 个答案:

答案 0 :(得分:1)

本案例中使用的User-Defined Variable @rn仅用于制作序列号列,如前一个问题的the answer中所述。

此处const未被用作关键字...所以不要被“ const - 融合”。它只是(select @rn := 0)的给定名称...它可以是任何其他名称,例如ABoopsaah,{{1 } ...(见下面的第二个链接)

请参阅以下链接中的示例用法,以便更好地了解User-Defined Variables

  • Create a Cumulative Sum Column in MySQL
  • MySql: Select Query- Make A Cumulative Sum Column
  • 答案 1 :(得分:0)

    坦率地说,所有这一切都是为了重置@rn变量。被“打包”成一个选择,以避免运行2个查询。 const意味着它是常量,因此只评估一次。

    删除它并在单个事务中添加更多查询时,可能会遇到麻烦。

    祝你好运

    泽索特