高频SQL使用知识点

  • having和where之间最大区别:having主要争对组,可与聚合函数连用having sun(factor>1000);where主要针对单行元素,无法与聚合函数连用;
  • node里面常用的时间格式转换:moment(npm包),标准格式化示例:moment.format;
  • SQL的常用时间转换格式:FROM_UNIXTIME(time,'%Y-%m-%d')
    //常用的一些时间函数查询
    //昨天
    select * from table_name where TO_DAYS(NOW())-TO_DAYS(时间字段名)<=1 * from table_name where TO_DAYS(NOW())-TO_DAYS(时间字段名)<=1
    //7天
    select * from table_name where DATE_SUB(CURDATE(),INTERVAL 7 DAYS)<= date(时间字段名) * from table_name where DATE_SUB(CURDATE(),INTERVAL 7 DAYS)<= date(时间字段名)
    //近30天
    select * from table_name where DATE_SUB(CURDATE(),INTERVAL 30 DAYS)<= date(时间字段名) * from table_name where DATE_SUB(CURDATE(),INTERVAL 30 DAYS)<= date(时间字段名)
    //当月
    select * from table_name where DATE_FORMAT(时间字段名,'%Y%m') = DATE_FORMAT(CURDATE(),'%Y%m') * from table_name where DATE_FORMAT(时间字段名,'%Y%m') = DATE_FORMAT(CURDATE(),'%Y%m')
    //上一月
    select * from table_name where PERIOD_OFF(date_format(now(),'%Y%m'),date_format(时间字段名,'%Y%m'))=1 * from table_name where PERIOD_OFF(date_format(now(),'%Y%m'),date_format(时间字段名,'%Y%m'))=1
  • group by在某些时候可以去重,会将完全相同的数据进行排序,即distinct
    SELECT *,SUM(money) as smoney FROM ngo_dog_log WHERE pid=11 GROUP BY smoney DESC *,SUM(money) as smoney FROM ngo_dog_log WHERE pid=11 GROUP BY smoney DESC
  • IN+数据,数据内容是select语句则只允许有一个字段,Exists前面则无字段,以select字段和值作为判定
  • 利用sql查询得到非原生新的数据字段尽量与原生数据做区分,如原生数据为money,新数据字段最好用smoney
  • select选择的元素利用(case when **** then ***end  )as new_strname
    SELECT id,value,pay_value,(case when sales_on='1' id,value,pay_value,(case when sales_on='1'
                              then 100then 100
                              when sales_on='0'when sales_on='0'
                              then 80then 80
                              endend
                              )as discount,as discount,
        from yh_productsfrom yh_products
        where type =2 and state =2where type =2 and state =2
        order by id descorder by id desc
  • 常用辅助函数:length, concat, substring, count, max, min,sum,floor/ceil
    //统计【】出现的频次
    select substring_index(left(title,INSTR(title,']')-1),']',-1) from 'xxx_table' substring_index(left(title,INSTR(title,']')-1),']',-1) from 'xxx_table'
    select substring_index(substring_index(title,'[',-1),']',-1) from 'xxx_table' substring_index(substring_index(title,'[',-1),']',-1) from 'xxx_table'
发布了14 篇原创文章 · 获赞 13 · 访问量 8702

猜你喜欢

转载自blog.csdn.net/sinat_20744625/article/details/98482166