2014-02-28 2 views
1

1 백만 개가 넘는 행이 있고 더 커질 수있는 데이터베이스 테이블이 있습니다. 이 데이터베이스 테이블에서 하나의 임의의 레코드를 잡을 데이터베이스를 쿼리하는 python 스크립트가 있습니다. 내가 사용하고있는 쿼리는 다음과 같습니다 :쿼리 속도 향상

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

더 좋은 방법이 있는지 궁금한가요? 그의 뛰어난 답변 마이클 벤자민에

감사 : 다음은 무작위 후 매우 빠른 오프셋 사용, 총을 기준으로 번호를 생성하는 그의 제안

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 number, number'가 마음에 들지 않습니다. – 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; 
[? 내가 RAND에 의해 MySQL의의 ORDER를 최적화하는 방법() 함수 (의
+0

"그룹 함수를 잘못 사용했습니다"가 반환됩니다. – developerwjk

+0

@developerwjk 업데이트 된 답변 확인 –