0

当我在脚本下面运行时,查询运行大约 30 秒,但是当它完成时,我可以获得经过时间等于 0.1 秒且计算时间为 2 毫秒的信息。

你能告诉我这个查询运行 30 秒的原因是什么,即使我不使用任何表?

declare heads bool;
declare heads_in_a_row int64 default 0; #number of heads in a row
declare nb_of_throws int64 default 0; #number of throws


#How many throws I need to get a 8 heads in a row?

while heads_in_a_row <= 8 DO

  set heads = RAND() < 0.5;
  set nb_of_throws = nb_of_throws +1;

    if heads then
      set heads_in_a_row = heads_in_a_row + 1 ;
    else
      set heads_in_a_row = 0;
    end if;

end while;

select nb_of_throws;
4

2 回答 2

0

这有时会很快,有时会很慢,这取决于随机机会达到连续 8 个正面的程度。连续尝试50个头,你会发现它慢得多,连续2个头会更快。您看到的 0.1s 已用时间仅是脚本最后部分的已用时间,该select语句仅提取您存储的变量值并且几乎是即时的。

于 2021-05-31T17:11:41.097 回答
0

你的答案是什么?我已经运行了几次,并在成百上千的“投掷”中得到了结果。连续 8 次正面朝上的几率是 0.39%,所以不太可能。BQ(以及一般的数据库)针对基于集合和基于列的计算进行了优化,而不是基于循环的操作。使用 BQ 解决这个问题可能不是您的最佳选择,例如 python 会快得多。

于 2021-05-31T19:33:32.670 回答