【mysql】獲取mysql中不重複的資料
阿新 • • 發佈:2018-12-15
假設情景如下:
user_table的欄位如下:
keyword \t c_time \t heat
keyword是字串的具有重複性的,c_time表示的是時間,heat是整形常數。
如下所示:
程式碼如下:
select keyword, max(created_at) as latest_created_at ,max(search_index) as latest_publish_time from data_table where created_at > DATE_SUB(now(),INTERVAL '1:30' HOUR_MINUTE) and keyword is not null and plateform_id=1 and search_index!=0 group by keyword limit 10;
上面的程式碼,先使用group by keyword 將相同keyword分成同一個組,然後使用max(created_at)將最新的資料獲取出來,會獲取到唯一的資料;本來就已經能夠得到一組唯一的資料了,但是又想獲得search_index欄位,所以要使用max(search_index),這樣才能得到search_index欄位。【這個是從group by陣列中獲得欄位的一種方式啊,雖然明明知道max(search_index)是沒什麼意義的,但是必須要是函式獲取欄位才不會報錯】。
然後使用:
created_at > DATE_SUB(now(),INTERVAL '1:30' HOUR_MINUTE)
上面的語句獲取到當前時間一個半小時的資料之內的資料,mysql可以直接使用">","<"來比較時間,越往後時間越大。然後在使用
keyword is not null
語句,將keyword 不為空。
這樣就獲得資料了。