我有一个数据库表,有超过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
可能重复http://stackoverflow.com/questions/1244555/how-can-i-optimize-mysqls-order-by-rand-function) – krokodilko