2013-03-20 82 views
1

我有一些數據在數據庫中,我需要排序時間上午/下午。無法排序時間(varchar類型)在上午/下午查詢

我的代碼

$current_dat=date("m/d/Y"); 

$ current_dat_short = SUBSTR($ current_dat,0,2);

$ rest = substr($ current_dat,-7,2);

$sql_timesheet=mysql_query('SELECT * FROM timesheet WHERE reg_id='.$regiD.' AND MONTH(date)='.$current_month.' AND YEAR(date)='.$current_year.' ORDER BY date DESC'); 
while($res_timesheet=mysql_fetch_array($sql_timesheet)){ 
    $projID=$res_timesheet['project']; 
    $taskID=$res_timesheet['task']; 
    $editableid=$res_timesheet['id']; 

上面的查詢由

01:20 AM 
01:25 PM   
03:25 AM 
03:40 AM 
04:20 PM 

排序時間,但我需要一個像

01:20 AM   
03:25 AM 
03:40 AM 
01:25 PM 
04:20 PM. 

PLS輸出也幫助我在這個問題上

+0

你不_actually_具有存儲爲'01:20 AM'時間值,你...? – CBroe 2013-03-20 11:00:09

+1

做*** NOT ***在varchar列中存儲時間。使用'TIME'數據類型。 – 2013-03-20 11:27:40

+0

@a_horse_with_no_name即使我嘗試過但沒有解決方案,直到現在,很奇怪請幫助 – Basky 2013-03-21 12:57:17

回答

2

爲此,您可以通過使用STR_TO_DATE函數MySQL

SELECT STR_TO_DATE('10.00pm','%h.%i%p'); 

試着改變你的查詢語句是這樣的:

更新: 聲明:

$sql_timesheet = mysql_query("SELECT * FROM timesheet WHERE reg_id=".$regiD." AND MONTH(date)=".$current_month." AND YEAR(date)=".$current_year." order by STR_TO_DATE(date,'%h.%i%p') desc,start_time asc"); 
+0

顯示錯誤爲「語法錯誤,行'中出現意外'%' – Basky 2013-03-20 11:11:46

+0

將語句更改爲sql_timesheet = mysql_query(」SELECT * FROM timesheet WHERE reg_id =「。$ regiD。」AND MONTH(date)=「。$ current_month。 「AND AND YEAR(date)=」。$ current_year。「order by STR_TO_DATE(date,'%h。%i%p')desc,start_time asc」);' – 2013-03-20 11:24:25

+0

感謝您回覆 – Basky 2013-03-21 12:53:26

相關問題