加快查询速度

时间:2014-02-28 23:47:31

标签: mysql

我有一个数据库表,它有超过100万行,可能会变大。我有一个python脚本,它查询数据库以从该数据库表中获取一个随机记录。我正在使用的查询是:

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

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

感谢Michael Benjamin的出色回答: 下面是我的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

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分:0)

尝试

SELECT * FROM customers 
WHERE id >= 
(SELECT FLOOR( MAX(id) * RAND()) FROM customers ) 
AND cust_type = 'C'
LIMIT 1;