2012-10-14 21 views
0

請注意,由於數據庫上的用戶和數據量很大,數據庫結構可能無法在沒有大量工作的情況下進行更改。難以確定哪個查詢實際上更快

的「朋友」表基本上是這樣的:

> show create table `friends` 
CREATE TABLE `friends` (
    `id` int(10) unsigned NOT NULL auto_increment, 
    `user1` int(10) unsigned NOT NULL, 
    `user2` int(10) unsigned NOT NULL, 
    PRIMARY KEY (`id`), 
    UNIQUE KEY `user1_2` (`user1`,`user2`), 
    KEY `user1` (`user1`), 
    KEY `user2` (`user2`) 
) ENGINE=InnoDB AUTO_INCREMENT=747908 

要獲取用戶的朋友,我有三種選擇:

  1. 單獨選擇user2其中user1等於用戶的ID和副反之亦然,然後在PHP中結合結果。
  2. SELECT IF([email protected],user2,user1) FROM friends WHERE @userid IN (user1,user2)
  3. SELECT user2 FROM friends WHERE [email protected]
    UNION SELECT user1 FROM friends WHERE [email protected]

我試圖定時選項2和3,而這正是我有一個問題:我第一次運行它,選項2需要約400ms的,而選項3只需要少於1ms。但是,每隔一段時間,opton 2需要0.6ms,option 2需要0.8ms。

我該怎麼辦?哪個選項實際上更快? EXPLAIN查詢返回:

id select_type table  type possible_keys key  key_len ref rows Extra 
1 SIMPLE  friends index NULL   user1_2 8  NULL 386438 Using where; Using index 

id select_type table  type possible_keys key  key_len ref rows Extra 
1 PRIMARY  friends ref user1,user1_2 user1_2 4  const 8  Using index 
2 UNION  friends ref user2   user2 4  const 8 
NULL UNION RESULT <union1,2> ALL NULL   NULL NULL NULL NULL 
+2

只是做一個腳本,運行每個querry 100萬次,看看哪個更快...... –

+0

恐怕不能真正回答我的問題,因爲我多次運行查詢並獲得截然不同的時間。 –

+1

你的意思是你跑了兩百萬次查詢並且查詢A更快,然後再次這樣做,查詢B更快? –

回答

2

像往常一樣在進行基準測試時,要小心高速緩存。

使用SQL_NO_CACHE從句(請參閱SELECT syntax)測量您的SELECT查詢。