从 mysql 随机 1000 行(不是重复行)的最佳方法是什么?
从 mysql 随机 1000 行(非重复行)的最佳方法是什么?
What is the best way to random 1000 row (not duplicate row) from mysql ?
Now i use this
1. get all data(id row) in to array.
2. Random position of array 1000 position.
3. i will get 1000 row (not duplicate row)
但是,这是非常缓慢的过程,
But, it's very slow process,
你有简单的方法来获得随机的 1000 行(不是重复的行)吗?
Do you have easy way to get random 1000 row (not duplicate row) ?
好吧,从评论中您也对理论上的答案感到满意.
Well from the comment you are also satisfied with a theoretical answer.
如果您的数组包含所有行,请使用 array_unique()
去掉重复的行然后使用 shuffle()
把它们混合起来,最后你可以用 array_slice()
.
If you have your array with all rows, use array_unique()
to get rid of duplicate rows then use shuffle()
to mix them up and at the end you can take a slice with array_slice()
.
当你已经没有选择重复的行时你可以改进它,那么你就不必使用array_unique()
.为此使用 DISTINCT
.如果您想在查询中完成所有操作,您可以执行以下操作:
You can improve it when you already don't select duplicate rows, then you don't have to use array_unique()
. For this use DISTINCT
. And if you want to do all in a query you can do something like this:
SELECT DISTINCT column FROM table
ORDER BY RAND()
LIMIT 1000