MySQL一些SQL技巧

1,一行轉多行

      url列以分號分隔,將其一行轉化爲多行,藉助自增長表help_topic 實現。
select a.channel_id,channel_code,site_name,siteid,refer_channel,substring_index(substring_index(a.url,';',b.help_topic_id+1),';',-1) as urls from  t_channel_mapping a join mysql.help_topic b on (length(a.url) - length(replace(a.url,';',''))+1) > b.help_topic_id; 
2,多行轉一行
     分組後彙總成一行,orderid以逗號分隔
  select SiteID,group_concat(distinct cast(orderid as char(8))) as orderid from  site_order group by SiteID

3,MYSQL實現rownumber
    mysql是不支持rownum函數,下面例子實現產品表中給產品一個順序編號

    select @rownum:=@rownum+1 rownum, product
    from 
   (
       select (@rownum:=0),a.product 
    from 
        (select  product from  t_proudct_info  GROUP BY product) a
    ) t


4, MYSQL實現FIRST_VALUE(t.url) over(partition by siteid,refer_channel)
   mysql中沒有類似oracle和postgreSQL的 OVER(PARTITION BY)功能,如下實現查詢每個分組中按url排序後第一個url

select siteid,refer_channel,substring_index(group_concat( t.url ),',',1)
from (
select siteid,refer_channel,url from t_channel_mapping  order by siteid,refer_channel,url
) t group by siteid,refer_channel

5,MYSQL常用日期函數

MySQL Date/Time to Str(日期/時間轉換爲字符串)函數:date_format(date,format), time_format(time,format)
select date_format('2008-08-08 22:23:01', '%Y%m%d%H%i%s');  
20080808222301 
MySQL Str to Date (字符串轉換爲日期)函數:str_to_date(str, format)
select str_to_date('08/09/2008', '%m/%d/%Y'); -- 2008-08-09
select str_to_date('08/09/08' , '%m/%d/%y'); -- 2008-08-09
select str_to_date('08.09.2008 08:09:30', '%m.%d.%Y %h:%i:%s'); -- 2008-08-09 08:09:30


date_add()函數向日期添加指定的時間間隔。
DATE_ADD(OrderDate,INTERVAL 2 DAY)
DATE_ADD(OrderDate,INTERVAL -2 MONTH)

DATEDIFF() 函數返回兩個日期之間的天數。
SELECT DATEDIFF('2008-12-30','2008-12-29') AS DiffDate

更多sql技術請關注  http://www.w3school.com.cn/sql/
發佈了137 篇原創文章 · 獲贊 340 · 訪問量 80萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章