我有一個數據庫表,有超過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