gpt4 book ai didi

mysql - 加快查询

转载 作者:行者123 更新时间:2023-11-29 05:24:09 25 4
gpt4 key购买 nike

我有一个数据库表,其中包含超过 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

最佳答案

根据总数随机生成一个数字,然后使用偏移量非常快。

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;

关于mysql - 加快查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22107969/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com