2014-02-28 141 views
1

我有一个数据库表,有超过100万行,可能会变大。我有一个python脚本查询数据库从这个数据库表中抓取一个随机记录。我使用的查询是:加快查询速度

SELECT * 
FROM customers 
WHERE cust_type = 'C' 
ORDER BY RAND() 
LIMIT 1; 

我只是想知道是否有一个更好,更快的方式做到这一点?

感谢迈克尔·本杰明为他的出色答卷: 下面是我的工作Python脚本,他建议

def util_get_random_customer_individual(): 
    # Gets a random customer from the MySQL DB Customers table. Users will need to parse items from the results into 
    # individual results 
    # Connect to the DB 
    config = {'user': 'user', 'password': 'password', 'host': 'host name', 
       'port': 3306, 'database': 'database'} 
    conn = mysql.connector.connect(**config) 
    c = conn.cursor() 
    type_code = 'I' 
    # Get a random customer based on the the count 
    c.execute('SELECT COUNT(*) FROM customers WHERE cust_type = %s', type_code) 
    count = c.fetchone()[0] 
    random_value = random.randint(1, count) 
    c.execute('SELECT * FROM customers WHERE cust_type = %s LIMIT %s, 1', (type_code, random_value,)) 
    random_customer = c.fetchone() 
    return random_customer 
+0

可能重复http://stackoverflow.com/questions/1244555/how-can-i-optimize-mysqls-order-by-rand-function) – krokodilko

回答

3

随机产生基于总的数字,然后使用偏移非常快。

SELECT COUNT(*) AS Total 
FROM customers 
WHERE cust_type='C'; 

PHP:

$rand = rand(1, $count); 

SELECT * 
FROM customer 
WHERE cust_type='C' 
LIMIT $rand, 1; 
+0

这对MySQL并不适用。不喜欢'LIMIT号码,号码' – developerwjk

+0

你的MySQL版本是什么? [MySQL 4.1+](https://dev.mysql.com/doc/refman/4.1/en/select.html)支持它。 –

+0

你运行的是哪个版本的mysql?旧版本可能需要'LIMIT 1 OFFSET ####' –

0

尝试

SELECT * FROM customers 
WHERE id >= 
(SELECT FLOOR(MAX(id) * RAND()) FROM customers) 
AND cust_type = 'C' 
LIMIT 1; 
[?如何优化MySQL的ORDER BY RAND()函数(的
+0

返回“无效的组功能使用” – developerwjk

+0

@developerwjk检查更新的答案 –