mysql中資料處理小技巧

2021-10-07 11:54:36 字數 2313 閱讀 7339

平時開發中經常與資料庫打交道,mysql又是現在比較常用的資料庫,此文總結下平時會用到的mysql的小技巧。

create table x like y;
快速建立和y結構一樣的表x

select last_insert_id()
處理資料時比較有用,比如插入一條資料後,要獲取插入資料的自增主鍵id,就可以使用last_insert_id()

可使用如下語句:

insert into table1(col1,col2)

select col1,col2 from table2

或使用如下語句:

insert into table1(col1,col2) 

values (1,2),(2,3),(3,4);

批量插入比單條插入效率要高很多。

可以把針對同乙個表的alter操作合併,提高效率

alter table tablename add column col1 int(11), add column col2 varchar(20);
不推薦使用 by rand();

可使用如下sql:

select * from users as t1 join (select round(rand()*(select max(id) 

from users)) as id) as t2 where t1.id>=t2.id order by t1.id limit 1;

select  curdate() #當前日期

select now() #當前時間

select year('2020-06-29 22:31:30') #獲取時間的年份

select month('2020-06-29 22:31:30') #獲取時間的月份

select day('2020-06-29 22:31:30') #獲取時間的天數

select hour('2020-06-29 22:31:30') #獲取時間的小時

select minute('2020-06-29 22:31:30') #獲取時間的分鐘

select second('2020-06-29 22:31:30') #獲取時間的秒數

select date_sub(now(),interval 1 year)  #在目前的時間減去一年

select date_add(now(),interval 1 year)  #在目前的時間上加上一年

select unix_timestamp('2020-06-29') #字串轉換成時間戳

select from_unixtime(1593360000) #時間戳轉化為時間

select date_format('2020-06-29 22:31:30', '%y-%m-%d %h:%i:%s') #字串轉化為時間格式

ifnull(expr1,expr2)

用法:假如expr1不為null,則 ifnull() 的返回值為expr1; 否則其返回值為 expr2。

isnull(expr) 

用法:如expr 為null,那麼isnull() 的返回值為 1,否則返回值為 0。

查詢name欄位中以'zh'開頭的資料:

select name from users where name regexp '^zh';
查詢name欄位中以'ng'結尾的資料:

select name from users where name regexp 'ng$';
查詢name欄位中包含'li'字串的資料:

select name from users where name regexp 'li';
set @cur = now();

select date_format(now(), '%y-%m-%d'), date_format(date_add(@cur,interval 1 day), '%y-%m-%d');

select

user.*, (@rownum := @rownum + 1) as rownum

from

user

inner join (select @rownum := 0) r

where

1order by

user.id;

R語言 資料處理 R做資料處理中的小技巧

一 主要內容 建立新變數 修改資料 修改變數名 處理缺失值 資料排序 資料合併 資料篩選 抽樣二 r語言 rm list ls gc manager c 1,2,3,4,5 date c 10 24 08 10 28 08 10 1 08 10 12 08 5 1 09 country c us u...

python資料處理小技巧 2

1,拆分含有多種分隔符的字串 import re s sdjjg,jsa jjalg tjljl.ljei,jks dji 方法 使用s.split 分割單個符合 使用正規表示式的re.split 方法,一次性拆分字串,使用 號表示分割連續多個 newstr re.split r t s print...

資料處理技巧

1.相關分析後指標二選一怎麼選?相關分析後我們需要對高度相關的指標組進行處理,選擇原則如下 1 優先留下業務上更重要的指標。比如,歷史購買總金額與歷史購買次數高度相關了,由於某次分析的目的是尋找重點客戶 目標導向很重要,這個需要與業務方進行溝通,統一業務口徑 所以這次分析中歷史購買總金額指標在重要性...