天天看點

sql 常用函數

不存在就建立

sql 常用函數

create table if not exists `basegraphics` (  

  `id` int(10) not null auto_increment,  

  `content` text not null comment '文本内容',  

  `src` varchar(100) not null comment '圖檔位址',  

  `width` varchar(30) not null comment '圖檔寬度',  

  `height` varchar(30) not null comment '圖檔高度',  

  `createtime` int(10) unsigned not null default '0',  

  primary key (`id`)  

) engine=innodb  default charset=utf8 ;   

distinct 替換group by

sql 常用函數

select count(1) from (select order_id from `sales_flat_order_item` group by order_id)a;  

select count(distinct order_id) from `sales_flat_order_item`;  

show create table name 即可檢視建表sql語句

show columns from  package;

上一條

sql 常用函數

select * from a where id < $id order by id desc limit  1    

下一條

sql 常用函數

select * from a where id > $id order by id asc limit  1  

insert into persons values ('1, 'bill', 'xuanwumen 10', 'beijing')

如果有字段自增和預設值可寫成:

insert into persons values ('bill', 'xuanwumen 10');

說明:兩張關聯表,删除主表中已經在副表中沒有的資訊

sql 常用函數

delete from info where not exists ( select * from infobz where info.infid=infobz.infid )   

lpad (str,len,padstr)

傳回字元串 str, 其左邊由字元串padstr 填補到len 字元長度。假如str 的長度大于len, 則傳回值被縮短至 len 字元。

sql 常用函數

mysql> select lpad('hi',4,'?');-> '??hi'  

mysql> select lpad('hi',1,'?');-> 'h'  

rpad(str,len,padstr)

傳回字元串str, 其右邊被字元串 padstr填補至len 字元長度。假如字元串str 的長度大于 len,則傳回值被縮短到與 len 字元相同長度。

insert(str,pos,len,newstr)

傳回字元串 str, 其子字元串起始于 pos 位置和長期被字元串 newstr取代的len 字元。 如果pos 超過字元串長度,則傳回值為原始字元串。 假如len的長度大于其它字元串的長度,則從位置pos開始替換。若任何一個參數為null,則傳回值為null。

sql 常用函數

mysql> select insert('quadratic', 3, 4, 'what');-> 'quwhattic'  

mysql> select insert('quadratic', -1, 4, 'what');-> 'quadratic'  

mysql> select insert('quadratic', 3, 100, 'what');-> 'quwhat'  

length(str)

傳回值為字元串str 的長度,機關為位元組。一個多位元組字元算作多位元組。這意味着 對于一個包含5個2位元組字元的字元串, length() 的傳回值為 10, 而 char_length()的傳回值則為5。

sql 常用函數

mysql> select length('text');-> 4  

repeat(str,count)

傳回一個由重複的字元串str 組成的字元串,字元串str的數目等于count 。若 count <= 0,則傳回一個空字元串。若str 或 count 為 null,則傳回 null 。

sql 常用函數

mysql> select repeat('mysql', 3);-> 'mysqlmysqlmysql'  

測試表資料 

sql 常用函數

greatest(求最大值)和least(求最小值)

sql 常用函數

mysql> select c_id, greatest( num1, num2 ) as max, num1, num2 from comment where  

 num1 != "" and num2 != "";  

+------+------+------+------+  

| c_id | max  | num1 | num2 |  

|    1 |   21 |   21 |   12 |  

|    2 |  219 |  133 |  219 |  

|    3 |   67 |   67 |   16 |  

3 rows in set (0.00 sec)  

mysql> select c_id, least( num1, num2 ) as max, num1, num2 from comment where nu  

m1 != "" and num2 != "";  

|    1 |   12 |   21 |   12 |  

|    2 |  133 |  133 |  219 |  

|    3 |   16 |   67 |   16 |  

interval函數

sql 常用函數

mysql> select * from comment where   datetime  <= (select now( ) - interval 10 h  

our as time_start );  //10個小時前評論的資料  

+------+------+-------+------------+---------------------+------+------+  

| c_id | u_id | name  | content    | datetime            | num1 | num2 |  

|    1 |    1 | test  | 2222222211 | 2010-11-10 15:16:00 |   21 |   12 |  

|    2 |    1 | test2 | tank       | 2010-11-10 15:01:00 |  133 |  219 |  

|    3 |    2 | tank  | zhangy     | 2010-11-10 15:11:00 |   67 |   16 |  

regexp函數

sql 常用函數

mysql> select * from `comment` where content regexp '[0-9]+';  

+------+------+------+------------+---------------------+------+------+  

| c_id | u_id | name | content    | datetime            | num1 | num2 |  

|    1 |    1 | test | 2222222211 | 2010-11-10 15:16:00 |   21 |   12 |  

1 row in set (0.00 sec)  

ifnull(expr1,expr2) 

如果expr1不是null,ifnull()傳回expr1,否則它傳回expr2。 ifnull()傳回一個數字或字元 串值,取決于它被使用的上下文環境 。

sql 常用函數

mysql > select ifnull(1,0);  

-> 1  

mysql> select ifnull(0,10);  

-> 0  

mysql> select ifnull(1/0,10);  

-> 10  

mysql> select ifnull(1/0,'yes');  

-> 'yes'  

select ifnull (sum(qty),0) as sum from table

判斷字段值是否為null或者空串''

sql 常用函數

select * from `table_name' where ifnull(col_name,'')='';   

if(expr1,expr2,expr3) 

如果expr1是true(expr1<>0且expr1<>null),那麼if()傳回expr2,否則它傳回expr3。 if()傳回一個數字或字元串值,取決于它被使用的上下文。

sql 常用函數

mysql> select if(1>2,2,3);  

-> 3  

mysql> select if(1<2,'yes','no');  

mysql> select if(strcmp('test','test1'),'yes','no');  

-> 'no'  

expr1作為整數值被計算,它意味着如果你正在測試浮點或字元串值,你應該使用一個比較操作來做。

sql 常用函數

mysql> select if(0.1,1,0);  

mysql> select if(0.1<>0,1,0);  

在上面的第一種情況中,if(0.1)傳回0,因為0.1被變換到整數值, 導緻測試if(0)。這可能不是你期望的。在第二種情況中,比較測試原來的浮點值看它是否是非零,比較的結果被用作一個整數。

select * from stock_moves where  abs (qty)=1140

sql 常用函數

mysql> select concat(2,' test');  

-> '2 test'  

concat_ws() 函數, 表示concat with separator,即有分隔符的字元串連接配接如連接配接後以逗号分隔

sql 常用函數

mysql> select concat_ws(';',2,' test');  

-> '2;test'  

coalesce() 函數表示可以傳回參數中的第一個非空表達式,當你有n個參數時選取第一個非空值(從左到右)。

sql 常用函數

mysql->select coalesce(null,"carrot","apple")  

->carrot  

mysql-> select coalesce(1,"carrot","apple")  

->1  

select coalesce(a,b,c);

如果a==null,則選擇b;

如果b==null,則選擇c;

如果a!=null,則選擇a;如果a b c 都為null ,則傳回為null(沒意義)。

instr(str,substr)

傳回字元串 str 中子字元串的第一個出現位置。這和locate()的雙參數形式相同,除非參

數的順序被颠倒。

sql 常用函數

mysql> select instr('foobarbar', 'bar');  

-> 4  

substring(str,pos) , substring(str from pos) substring(str,pos,len) ,

substring(str from pos for len)

不帶有len 參數的格式從字元串str傳回一個子字元串,起始于位置 pos。帶有len參數的格

式從字元串str傳回一個長度同len字元相同的子字元串,起始于位置 pos。 使用 from的格

式為标準 sql 文法。也可能對pos使用一個負值。假若這樣,則子字元串的位置起始于字

符串結尾的pos 字元,而不是字元串的開頭位置。在以下格式的函數中可以對pos 使用一

個負值。

sql 常用函數

mysql> select substring('quadratically',5);  

-> 'ratically'  

mysql> select substring('foobarbar' from 4);  

-> 'barbar'  

mysql> select substring('quadratically',5,6);  

-> 'ratica'  

mysql> select substring('sakila', -3);  

-> 'ila'  

substring_index(str,delim,count) 

在定界符 delim 以及count 出現前,從字元串str傳回自字元串。若count為正值,則傳回最終

定界符(從左邊開始)左邊的一切内容。若count為負值,則傳回定界符(從右邊開始)右邊

的一切内容。

sql 常用函數

mysql> select substring_index('www.mysql.com', '.', 2);  

-> 'www.mysql'  

mysql> select substring_index('www.mysql.com', '.', -2);  

-> 'mysql.com'  

sql 常用函數

create function substr_count(x varchar(255), delim varchar(12)) returns int  

return (length(x)-length(replace(x, delim, ''))) // select substr_count('abac','a');  

make_set(bits,str1,str2,...)

傳回一個設定值 (一個包含被‘,’号分開的字字元串的字元串) ,由在bits 組中具有相應的

比特的字元串組成。str1 對應比特 0, str2 對應比特1,以此類推。str1, str2, ...中的 null值不

會被添加到結果中。

sql 常用函數

mysql> select make_set(1,'a','b','c');  

-> 'a'  

mysql> select make_set(1 | 4,'hello','nice','world');  

-> 'hello,world'  

mysql> select make_set(1 | 4,'hello','nice',null,'world');  

-> 'hello'   

left(str,len)

傳回從字元串str 開始的len 最左字元。

sql 常用函數

mysql> select left('foobarbar', 5);-> 'fooba'  

elt(n,str1,str2,str3,...)   

如果n=   1,傳回str1,如果n=   2,傳回str2,等等。如果n小于1或大于參數個數,傳回null。elt()是field()反運算。

sql 常用函數

select   elt(1,   'ej ',   'heja ',   'hej ',   'foo ');  //->   'ej '  

replace(str,from_str,to_str)

傳回字元串str 以及所有被字元串to_str替代的字元串from_str 。

sql 常用函數

mysql> select replace('www.mysql.com', 'w', 'ww');  

-> 'wwwwww.mysql.com'   

update   set   date   =   replace(replace (replace(date,   "年 ",   "- "),   "月 ",   "- "),   "日 ",   " ");

1.例如:

sql 常用函數

select student_id,group_concat(courses_id order by courses_id desc) as courses_id from student_courses group by student_id;  

  +------------+-------------+  

  | student_id | courses_id  |  

  |          2 | 5,4,3            |    

2.當然分隔符還可以自定義,預設是以“,”作為分隔符,若要改為“|||”,則使用separator來指定,例如:

sql 常用函數

select student_id, group_concat(courses_id separator '|||') as courses from student_courses where student_id=2 group by student_id;  

+------------+---------+  

| student_id | courses |  

|   2        | 3|||4|||5    |  

 +------------+---------+       

group_concat([distinct] 要連接配接的字段 [order by asc/desc 排序字段] [separator '分隔符'])

union 的文法如下:

[sql 語句 1]

union

[sql 語句 2]

而我們要找 出來所有有營業額 (sales) 的日子。要達到這個目的,我們用以下的 sql 語句:

select date from store_information

select date from internet_sales

sql 常用函數

mysql> select * from sales;  

+-----+------------+--------+--------+--------+------+------------+  

| num | name       | winter | spring | summer | fall | category   |  

|   1 | java       |   1067 |    200 |    150 |  267 | holiday    |  

|   2 | c          |    970 |    770 |    531 |  486 | profession |  

|   3 | javascript |     53 |     13 |     21 |  856 | literary   |  

|   4 | sql        |    782 |    357 |    168 |  250 | profession |  

|   5 | oracle     |    589 |    795 |    367 |  284 | holiday    |  

|   6 | mysql      |    953 |    582 |    336 |  489 | literary   |  

|   7 | cplus      |    752 |    657 |    259 |  478 | literary   |  

|   8 | python     |     67 |     23 |     83 |  543 | holiday    |  

|   9 | php        |    673 |     48 |    625 |   52 | profession |  

9 rows in set (0.01 sec)  

mysql> select name as name,  

    -> case category  

    -> when "holiday" then "seasonal"  

    -> when "profession" then "bi_annual"  

    -> when "literary" then "random" end as "pattern"  

    -> from sales;  

+------------+-----------+  

| name       | pattern   |  

| java       | seasonal  |  

| c          | bi_annual |  

| javascript | random    |  

| sql        | bi_annual |  

| oracle     | seasonal  |  

| mysql      | random    |  

| cplus      | random    |  

| python     | seasonal  |  

| php        | bi_annual |  

9 rows in set (0.00 sec)