2010-07-16 19 views
2

我有簡單的功能由一個SQL查詢MySQL的不使用功能指標

CREATE FUNCTION `GetProductIDFunc`(in_title char (14)) 
     RETURNS bigint(20) 
BEGIN 
    declare out_id bigint;  

    select id into out_id from products where title = in_title limit 1;  
    RETURN out_id; 
END 

該函數的執行時間需要5秒

select Benchmark(500 ,GetProductIdFunc('sample_product')); 

平原查詢的執行時間花費0.001秒

select Benchmark(500,(select id from products where title = 'sample_product' limit 1)); 

「標題」字段被索引。爲什麼功能執行需要很多時間,我如何優化它?

編輯: 執行計劃

mysql> EXPLAIN EXTENDED select id from products where title = 'sample_product' limit 1; 
+----+-------------+----------+-------+---------------+------------+---------+-------+------+----------+-------------+ 
| id | select_type | table | type | possible_keys | key  | key_len | ref | rows | filtered | Extra  | 
+----+-------------+----------+-------+---------------+------------+---------+-------+------+----------+-------------+ 
| 1 | SIMPLE  | products | const | Index_title | Index_title | 14  | const | 1 | 100.00 | Using index | 
+----+-------------+----------+-------+---------------+------------+---------+-------+------+----------+-------------+ 
1 row in set, 1 warning (0.00 sec) 

mysql> EXPLAIN select GetProductIdFunc('sample_product'); 
+----+-------------+-------+------+---------------+------+---------+------+------+----------------+ 
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra   | 
+----+-------------+-------+------+---------------+------+---------+------+------+----------------+ 
| 1 | SIMPLE  | NULL | NULL | NULL   | NULL | NULL | NULL | NULL | No tables used | 
+----+-------------+-------+------+---------------+------+---------+------+------+----------------+ 
1 row in set (0.00 sec) 
+0

可以包括執行計劃? – MJB 2010-07-16 14:32:22

回答

2

這可能是一個字符集問題。如果該函數使用與表列不同的字符集,則儘管存在索引,但仍會導致性能非常低下。

運行show create table products\G來確定列的字符集。

運行show variables like 'character_set%';查看相關的默認字符集是爲您的數據庫。

+0

輝煌。 如何強制過程使用正確的字符集。 – 2010-07-16 14:58:57

+0

您可以爲輸入參數指定一個字符集。例如'CREATE FUNCTION GetProductIDFunc(in_title char(14)charset utf8)...' – 2010-07-16 15:04:49

+0

另一種選擇是在與標題進行比較時顯式轉換in_title的字符集:'select id into out_id from title = convert(in_title using utf8)限制1;' – 2010-07-16 15:06:15

0

試試這個:

CREATE FUNCTION `GetProductIDFunc`(in_title char (14)) 
     RETURNS bigint(20) 
BEGIN 
    declare out_id bigint;  

    set out_id = (select id from products where title = in_title limit 1);  
    RETURN out_id; 
END 
+0

沒有改變。 – 2010-07-16 15:03:49