Re: [MySQL ] 撈日期的問題

看板Database作者 (肯先生)時間15年前 (2009/05/21 15:27), 編輯推噓2(201)
留言3則, 3人參與, 最新討論串5/8 (看更多)
※ 引述《TonyQ (沉默是金)》之銘言: : ※ 引述《vitolee (毅)》之銘言: : : 今天我的資料儲存方式如下 : : Class 使用人數 Date : : A 43 2009/05/09 18:04:25 : 如果是 datetime 欄位 , 可以直接用 hour 來作判斷比較直覺. : 像你要 18點間上課的資料 , 就可以寫 : SELECT * FROM `table_date` WHERE hour( date ) =18 建議用 explain 看一下,即使把 Date 設定了 index,應該還會有一個 full table scan,資料一多,就很慢: mysql> explain SELECT * FROM t WHERE HOUR(date)='6'\G Connection id: 14782064 Current database: xxxx *************************** 1. row *************************** id: 1 select_type: SIMPLE table: t type: ALL possible_keys: NULL key: NULL key_len: NULL ref: NULL rows: 1735 Extra: Using where 1 row in set (0.00 sec) 用 substring 也是一樣的結果: mysql> explain SELECT * FROM t WHERE substring(`Date`,12,2)='18'\G ERROR 2006 (HY000): MySQL server has gone away No connection. Trying to reconnect... Connection id: 14784890 Current database: xxxx *************************** 1. row *************************** id: 1 select_type: SIMPLE table: t type: ALL possible_keys: NULL key: NULL key_len: NULL ref: NULL rows: 1735 Extra: Using where 1 row in set (0.01 sec) 所以建議你把 hour 額外放一個欄位,搜尋的時候,用 hour 那個欄位 去搜就好,當然,也要事先設定好 index: mysql> explain SELECT * FROM t WHERE hour=6\G Connection id: 14782312 Current database: xxxx *************************** 1. row *************************** id: 1 select_type: SIMPLE table: t type: ref possible_keys: hour key: hour key_len: 1 ref: const rows: 39 Extra: 1 row in set (0.00 sec) mysql> 這只是要證明一下 date 有設 index 的: mysql> explain SELECT * FROM t WHERE date BETWEEN '2009-05-18 00:00:00' AND '2009-05-18 12:00:00'\G Connection id: 14782658 Current database: xxxx *************************** 1. row *************************** id: 1 select_type: SIMPLE table: t type: range possible_keys: Date key: Date key_len: 8 ref: NULL rows: 10 Extra: Using where 1 row in set (0.00 sec) mysql> -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 122.116.151.252 ※ 編輯: KC73 來自: 122.116.151.252 (05/21 15:35)

05/21 16:42, , 1F
感謝分享o(_ _)o
05/21 16:42, 1F

05/21 17:44, , 2F
基本上只要對欄位做了 function 處理.都會造成table scan.
05/21 17:44, 2F

05/21 18:06, , 3F
對呀!所以那些 function,最好都不要放在 WHERE 後面。
05/21 18:06, 3F
然後 mysql 的 index 有點麻煩。 欄位在 index 的前後順序,還有欄位會不會拿來排序,對效能的影響都很大; index 設定多了以後,INSERT (或 UPDATE、REPLACE) 的速度就會變慢。 一開始最好每個 SELECT 都拿來 EXPLAIN 一次。 ※ 編輯: KC73 來自: 122.116.151.252 (05/21 18:18)
文章代碼(AID): #1A5G9g_r (Database)
討論串 (同標題文章)
文章代碼(AID): #1A5G9g_r (Database)