2014-02-28 145 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檢查更新的答案 –