在这个例子中,尝试使用 Mysql 来计算频率 php


Trying to use Mysql to count frequency in this example php?

我的示例表如下。我有4个苹果,第一个苹果和第二个苹果之间有两行,第二个苹果和第三个苹果之间有一排,第三个苹果和第四个苹果之间有两行。是否可以使用 Mysql 知道每个苹果和下一个苹果之间有多少行。

id      fruit
1        berry
2        apple
3        bananan
4        berry
5        apple
6        berry
7        apple
8        berry
9        berry
10       apple

这将计算每个苹果和下一个苹果之间的 ID 差异。

SELECT a.id, MIN(b.id)-a.id AS diff
FROM yourTable AS a
JOIN yourTable AS b ON a.id < b.id
WHERE a.fruit = 'apple'
AND b.fruit = 'apple'
GROUP BY a.id

请注意,如果 ID 序列中存在间隙,则会计算差异中缺少的 ID。