本文共 18886 字,大约阅读时间需要 62 分钟。
net start mysqlmysql -uroot -pshow databasesuse 数据库名how tables--------------------------------------------------------------------------select goods_id ,goods_name ,shop_price+1,market_price,market_price-shop_price from goods;select * from goods where goods_id = 32;select goods_id,goods_name,cat_id from goods where cat_id <> 32;//不等于select goods_id,goods_name,cat_id from goods where cat_id > 32;//不等于select goods_id,goods_name,cat_id from goods where cat_id <= 32 and cat_id >= 2;//不等于select goods_id,cat_id from goods where cat_id = 4 or cat_id =11;//或者select goods_id,cat_id from goods where cat_id in (4,11);//4,11选一个select goods_id,cat_id from goods where cat_id between 4 and 11;//4--11之间select goods_id,cat_id from goods where cat_id not in (4,11);//不是4,11select click_count ,cat_id,shop_price from goods where cat_id = 3 and (shop_price < 1000 or shop_price > 3000) and click_count>5; //and优先级高于orselect goods_name from goods where goods_name like '诺基亚%';//%是任意字符select goods_name from goods where goods_name like '诺基亚___';//___3个下划线是3个字符select cat_id,sum(goods_number*shop_price) as k from goods group by cat_id having k>20000(5个聚合函数,sum,avg,max,min,count与group综合运用) select cat_id,max(shop_price) from ecs_goods group by cat_id;select goods_id,cat_id,goods_name,shop_price from ecs_goods where cat_id=3 and shop_price>1000 and shop_price <3000 and click_count>5 and goods_name like '诺基亚%';select goods_id,cat_id,goods_name,shop_price from ecs_goods where shop_price between 1000 and 3000 and cat_id=3 and click_count>5 and goods_name like '诺基亚%';select goods_id,cat_id,goods_name,shop_price from ecs_goods where goods_name like '诺基亚N__';select goods_id,cat_id,goods_name,shop_price from ecs_goos where goods_name not like '诺基亚%';select goods_id,cat_id,goods_name,shop_price,click_count from ecs_goods where cat_id=3 and (shop_price <1000 or shop_price>3000) and click_count>5;select goods_id,cat_id,goods_name,shop_price from ecs_goods where cat_id not in (3,11);取出100<=价格<=500的商品(不许用and)select goods_id,cat_id,goods_name,shop_price from ecs_goods where shop_price between 100 and 500;1.15 一道面试题,有如下表和数组,把num值处于[20,29]之间,改为20,num值处于[30,39]之间的,改为30select floor(num/10)*10 from mian;updata mian set num=floor(num/10)*10;update mian set num=floor(num/10)*10 where num between 20 and 29;1.16 练习题:把good表中商品名为'诺基亚xxxx'的商品,改为'HTCxxxx',update goods set goods_name = concat('htc',substring(goods_name,4)) where goods_name like '诺基亚%';------------------------------------------------------------------------------------------------------NULL : insert into user values (1,null,99,'rr');//Column 'name' cannot be nullmysql> create table tmp( -> id int, -> name varchar(20) -> ) charset utf8 engine myisam;insert into tmp values (1,'ll'),(2,'ffff'),(3,null);mysql> select * from tmp;+----+------+| id | name |+----+------+| 1 | ll || 1 | ll || 2 | ffff || 3 | NULL |+----+------+4 rows in setmysql> select * from tmp where name = null;Empty setmysql> select * from tmp where name != null;Empty setmysql> select * from tmp where name is null;+----+------+| id | name |+----+------+| 3 | NULL |+----+------+1 row in setmysql> select * from tmp where name is not null;+----+------+| id | name |+----+------+| 1 | ll || 1 | ll || 2 | ffff |+----+------+3 rows in setmysql> desc tmp;//查看表的结构: +-------+-------------+------+-----+---------+-------+| Field | Type | Null | Key | Default | Extra |+-------+-------------+------+-----+---------+-------+| id | int(11) | YES | | NULL | || name | varchar(20) | YES | | NULL | |+-------+-------------+------+-----+---------+-------+2 rows in setmysql> show create table tmp;//查看表的创建过程: +-------+---------------+| Table | Create Table |+-------+--------------+| tmp | CREATE TABLE `tmp` ( `id` int(11) DEFAULT NULL, `name` varchar(20) DEFAULT NULL) ENGINE=MyISAM DEFAULT CHARSET=utf8 |+-------+------------+1 row in set----------------------------------------------------------------------------------------------------------mysql> select avg(shop_price) from goods;mysql> select count(*) from goods;mysql> select sum(goods_number*shop_price) from goods;//求2列相乘后的和mysql> select avg(shop_price) ,cat_id from goods group by cat_id;//先根据cat_id分组,再求每组的平均值。+-----------------+--------+| avg(shop_price) | cat_id |+-----------------+--------+| 823.330000 | 2 || 1746.066667 | 3 || 2297.000000 | 4 || 3700.000000 | 5 || 75.333333 | 8 || 31.000000 | 11 || 33.500000 | 13 || 54.000000 | 14 || 70.000000 | 15 |+-----------------+--------+9 rows in setmysql> select count(*) ,cat_id from goods group by cat_id;//根据cat_id分组,再查每组的数量。+----------+--------+| count(*) | cat_id |+----------+--------+| 1 | 2 || 15 | 3 || 3 | 4 || 1 | 5 || 3 | 8 || 2 | 11 || 2 | 13 || 2 | 14 || 2 | 15 |+----------+--------+9 rows in setmysql> select max(shop_price) ,cat_id from goods group by cat_id;+-----------------+--------+| max(shop_price) | cat_id |+-----------------+--------+| 823.33 | 2 || 5999 | 3 || 2878 | 4 || 3700 | 5 || 100 | 8 || 42 | 11 || 48 | 13 || 90 | 14 || 95 | 15 |+-----------------+--------+9 rows in setmysql> select goods_id, goods_name, market_price - shop_price from goods;+----------+---------------------------+---------------------------+| goods_id | goods_name | market_price - shop_price |+----------+---------------------------+---------------------------+| 1 | kd876 | 277.6 || 4 | htcn85原装充电器 | 11.6 |+----------+---------------------------+---------------------------+31 rows in set-------------------------------------------------------------------------------------------------------having对结果集操作: where---group by---having---order by ---limit数据库数据保存在goods.MYD文件里面,select xxx from goods where cat_id=3 查询的临时结果集result放在内存中,where是针对表起作用,select (market_price - shop_price) as less中的less在内存结果集中不在表中,所以对表中where less > 700不起作用,想好针对结果集发挥作用只能用having了,mysql> select goods_id, goods_name ,(market_price - shop_price) as less from goods [where 1] having less > 700;+----------+----------------+--------+| goods_id | goods_name | less |+----------+----------------+--------+| 22 | 多普达touch hd | 1199.8 || 23 | htcn96 | 740 |+----------+----------------+--------+2 rows in set所以where不能写在having后面,因为只有where从表中查询出结果集后,然后用having对结果集操作。有如下表及数据+------+---------+-------+| name | subject | score |+------+---------+-------+| 张三 | 数学 | 90 || 张三 | 语文 | 50 || 张三 | 地理 | 40 || 李四 | 语文 | 55 || 李四 | 政治 | 45 || 王五 | 政治 | 30 |+------+---------+-------+ 要求:查询出2门及2门以上不及格者的平均成绩drop table tmp;mysql> select count(score<=60) as num from temp;+-----+| num |+-----+| 6 |+-----+1 row in setmysql> select count(score<=60) as num from temp group by name;+-----+| num |+-----+| 3 || 1 || 2 |+-----+3 rows in setmysql> select name, count(score<=60) as num, avg(score) from temp where 1 group by name having num>=2;+------+-----+------------+| name | num | avg(score) |+------+-----+------------+| 三 | 3 | 60.0000 || 四 | 2 | 30.0000 |+------+-----+------------+-------------------------------------------------------------------------------------------------------order by:在内存中排序mysql> select * from goods order by shop_price , cat_id;取出点击量前三名到前5名的商品select goods_id,goods_name,click_count from ecs_goods order by click_count desc limit 2,5;//跳过2个从第三个开始,取出5个,where 子查询:查询出最新的商品(以商品编号goods_id最大为最新,用子查询实现)select goods_id,goods_name from goods where goods_id =(select max(goods_id) from ecs_goods);查询出每一个cat_id下最新的商品(先查询每个cat_id下goods_id的最大值)mysql> select goods_id,cat_id from goods where goods_id in (select max(goods_id) from goods group by cat_id) order by cat_id asc;from子查询:mysql> select goods_id from (select goods_id,goods_name from goods order by goods_id asc, goods_name desc) as temp where goods_id between 10 and 13;+----------+| goods_id |+----------+| 10 || 11 || 12 || 13 |+----------+mysql> select goods_id as gid from (select goods_id,goods_name from goods order by goods_id asc, goods_name desc) as temp where goods_id between 10 and 13 order by gid desc limit 1,2;//有的地方要加as不加as不行, 空格作为分隔符逗号作为连接符。+-----+| gid |+-----+| 12 || 11 |+-----+exists型子查询:查出所有有商品的栏目cart_idselect * from category where exists (select * from goods where goods.cat_id=category.cat_id);mysql> select goods.cat_id,category.cat_id from goods,category where goods.cat_id = category.cat_id limit 1,5;//2个表查询+--------+--------+| cat_id | cat_id |+--------+--------+| 8 | 8 || 8 | 8 || 11 | 11 || 11 | 11 || 8 | 8 |+--------+--------+-----------------------------------------------------------------------------------------------------------------1+N模式查询:------------------------------------------------------------------------------------------------------------------连接查询:左连接,left join on,table A left join table B on tableA.col1 = tableB.col2 ; 连接完了之后就成了一个大表格(from boy left join girl on boy.hid=girl.hid就是一张大表,后面的写法跟一张表一样写法,)。on是表连接的条件。mysql> select * from girl; mysql> select * from boy;+-----+--------+ +-----+--------+| hid | gname | | hid | bname |+-----+--------+ +-----+--------+| B | 小龙女 | | A | 屌丝 || C | 张柏芝 | | B | 杨过 || D | mv | | C | 陈冠希 || E | no | | D | yw |+-----+--------+ +-----+--------+mysql> select boy.hid,boy.bname,girl.hid,girl.gname from boy left join girl on boy.hid=girl.hid;//左边的表全部列出来,进行右边表的匹配,匹配不上就没有,+-----+--------+------+--------+| hid | bname | hid | gname |+-----+--------+------+--------+| B | 杨过 | B | 小龙女 || C | 陈冠希 | C | 张柏芝 || D | yw | D | mv || A | 屌丝 | NULL | NULL |+-----+--------+------+--------+mysql> select boy.hid,boy.bname,girl.hid,girl.gname from boy right join girl on boy.hid=girl.hid;//右边的表全部列出来,进行左边表的匹配,匹配不上就没有,+------+--------+-----+--------+| hid | bname | hid | gname |+------+--------+-----+--------+| B | 杨过 | B | 小龙女 || C | 陈冠希 | C | 张柏芝 || D | yw | D | mv || NULL | NULL | E | no |+------+--------+-----+--------+mysql> select boy.hid,boy.bname,girl.hid,girl.gname from boy inner join girl on boy.hid=girl.hid;//剔除没有匹配上的,inner join是求交集,求并集是外连接,mysql没有外连接,oracle和sqlsercver有外连接。+-----+--------+-----+--------+| hid | bname | hid | gname |+-----+--------+-----+--------+| B | 杨过 | B | 小龙女 || C | 陈冠希 | C | 张柏芝 || D | yw | D | mv |+-----+--------+-----+--------+select goods_name,cat_name,shop_price from goods left join category on goods.cat_id=category.cat_id //大表,where goods.cat_id = 4;mysql> select * from boygirl;+--------+--------+| boygid | byname |+--------+--------+| A | aaa || B | bbb || C | ccc || D | ddd |+--------+--------+mysql> select * from boy left join girl on gid=bid;+-----+--------+------+--------+| bid | bname | gid | gname |+-----+--------+------+--------+| B | 杨过 | B | 小龙女 || C | 陈冠希 | C | 张柏芝 || D | yw | D | mv || A | 屌丝 | NULL | NULL |+-----+--------+------+--------+mysql> select * from boy left join girl on gid=bid //left join成一张大表,这张大表再去右连接,right join boygirl on boygid=gid;+------+--------+------+--------+--------+--------+| bid | bname | gid | gname | boygid | byname |+------+--------+------+--------+--------+--------+| B | 杨过 | B | 小龙女 | B | bbb || C | 陈冠希 | C | 张柏芝 | C | ccc || D | yw | D | mv | D | ddd || NULL | NULL | NULL | NULL | A | aaa |+------+--------+------+--------+--------+--------+mysql> select * from boy left join girl as tmp on gid=bid right join boygirl on boygirl.boygid=tmp.gid;//取boy left join girl大表的别名为tmp,+------+--------+------+--------+--------+--------+| bid | bname | gid | gname | boygid | byname |+------+--------+------+--------+--------+--------+| B | 杨过 | B | 小龙女 | B | bbb || C | 陈冠希 | C | 张柏芝 | C | ccc || D | yw | D | mv | D | ddd || NULL | NULL | NULL | NULL | A | aaa |+------+--------+------+--------+--------+--------+mysql> select * from boy left join girl as t1 on boy.bid = t1.gid;//t1为girl的别名。+-----+--------+------+--------+| bid | bname | gid | gname |+-----+--------+------+--------+| B | 杨过 | B | 小龙女 || C | 陈冠希 | C | 张柏芝 || D | yw | D | mv || A | 屌丝 | NULL | NULL |+-----+--------+------+--------+select gc.goods_name,gc.cat_name,gb.brand_name from goods left join category as gcon goods.cat_id=category.cat_idleft join brand as gbon goods.brand_id=brand.brand_idwhere goods.cat_id = 4;----------------------------------------------------------------------------------------------------union查询:把多个sql的查询结果合并成一个结果集。必须满足表的列数相同。字段不同都可以,以前面表格的字段为新字段。完全相同的行将会被合并,union all就不会合并完全相同的行。mysql> select * from study_new union all select * from m;+----+----------+-------+-----+------------+| id | username | class | sex | addtime |+----+----------+-------+-----+------------+| 1 | 小王 | 1 | 男 | 0 || 2 | 小四 | 2 | 女 | 0 || 1 | 1 | 2 | 2:0 | 2006-05-21 || 2 | 2 | 3 | 1:2 | 2006-06-21 || 3 | 3 | 1 | 2:5 | 2006-06-25 || 4 | 2 | 1 | 3:2 | 2006-07-21 |+----+----------+-------+-----+------------+
一、数学函数abs(x) 返回x的绝对值bin(x) 返回x的二进制(oct返回八进制,hex返回十六进制)ceiling(x) 返回大于x的最小整数值exp(x) 返回值e(自然对数的底)的x次方floor(x) 返回小于x的最大整数值greatest(x1,x2,...,xn)返回集合中最大的值least(x1,x2,...,xn) 返回集合中最小的值ln(x) 返回x的自然对数log(x,y)返回x的以y为底的对数mod(x,y) 返回x/y的模(余数)pi()返回pi的值(圆周率)rand()返回0到1内的随机值,可以通过提供一个参数(种子)使rand()随机数生成器生成一个指定的值。round(x,y)返回参数x的四舍五入的有y位小数的值sign(x) 返回代表数字x的符号的值sqrt(x) 返回一个数的平方根truncate(x,y) 返回数字x截短为y位小数的结果二、聚合函数(常用于group by从句的select查询中)avg(col)返回指定列的平均值count(col)返回指定列中非null值的个数min(col)返回指定列的最小值max(col)返回指定列的最大值sum(col)返回指定列的所有值之和group_concat(col) 返回由属于一组的列值连接组合而成的结果三、字符串函数ascii(char)返回字符的ascii码值bit_length(str)返回字符串的比特长度concat(s1,s2...,sn)将s1,s2...,sn连接成字符串concat_ws(sep,s1,s2...,sn)将s1,s2...,sn连接成字符串,并用sep字符间隔insert(str,x,y,instr) 将字符串str从第x位置开始,y个字符长的子串替换为字符串instr,返回结果find_in_set(str,list)分析逗号分隔的list列表,如果发现str,返回str在list中的位置lcase(str)或lower(str) 返回将字符串str中所有字符改变为小写后的结果left(str,x)返回字符串str中最左边的x个字符length(s)返回字符串str中的字符数ltrim(str) 从字符串str中切掉开头的空格position(substr,str) 返回子串substr在字符串str中第一次出现的位置quote(str) 用反斜杠转义str中的单引号repeat(str,srchstr,rplcstr)返回字符串str重复x次的结果reverse(str) 返回颠倒字符串str的结果right(str,x) 返回字符串str中最右边的x个字符rtrim(str) 返回字符串str尾部的空格strcmp(s1,s2)比较字符串s1和s2trim(str)去除字符串首部和尾部的所有空格ucase(str)或upper(str) 返回将字符串str中所有字符转变为大写后的结果四、日期和时间函数curdate()或current_date() 返回当前的日期curtime()或current_time() 返回当前的时间date_add(date,interval int keyword)返回日期date加上间隔时间int的结果(int必须按照关键字进行格式化),如:selectdate_add(current_date,interval 6 month);date_format(date,fmt) 依照指定的fmt格式格式化日期date值date_sub(date,interval int keyword)返回日期date加上间隔时间int的结果(int必须按照关键字进行格式化),如:selectdate_sub(current_date,interval 6 month);dayofweek(date) 返回date所代表的一星期中的第几天(1~7)dayofmonth(date) 返回date是一个月的第几天(1~31)dayofyear(date) 返回date是一年的第几天(1~366)dayname(date) 返回date的星期名,如:select dayname(current_date);from_unixtime(ts,fmt) 根据指定的fmt格式,格式化unix时间戳tshour(time) 返回time的小时值(0~23)minute(time) 返回time的分钟值(0~59)month(date) 返回date的月份值(1~12)monthname(date) 返回date的月份名,如:select monthname(current_date);now() 返回当前的日期和时间quarter(date) 返回date在一年中的季度(1~4),如select quarter(current_date);week(date) 返回日期date为一年中第几周(0~53)year(date) 返回日期date的年份(1000~9999)一些示例:获取当前系统时间:select from_unixtime(unix_timestamp());select extract(year_month from current_date);select extract(day_second from current_date);select extract(hour_minute from current_date);返回两个日期值之间的差值(月数):select period_diff(200302,199802);在mysql中计算年龄:select date_format(from_days(to_days(now())-to_days(birthday)),'%y')+0 as age from employee;这样,如果brithday是未来的年月日的话,计算结果为0。下面的sql语句计算员工的绝对年龄,即当birthday是未来的日期时,将得到负值。select date_format(now(), '%y') - date_format(birthday, '%y') -(date_format(now(), '00-%m-%d')100,'true','false');if()函数在只有两种可能结果时才适合使用。然而,在现实世界中,我们可能发现在条件测试中会需要多个分支。在这种情况下,mysql提供了case函数,它和php及perl语言的switch-case条件例程一样。case函数的格式有些复杂,通常如下所示:case [expression to be evaluated]when [val 1] then [result 1]when [val 2] then [result 2]when [val 3] then [result 3]......when [val n] then [result n]else [default result]end这里,第一个参数是要被判断的值或表达式,接下来的是一系列的when-then块,每一块的第一个参数指定要比较的值,如果为真,就返回结果。所有的when-then块将以else块结束,当end结束了所有外部的case块时,如果前面的每一个块都不匹配就会返回else块指定的默认结果。如果没有指定else块,而且所有的when-then比较都不是真,mysql将会返回null。case函数还有另外一种句法,有时使用起来非常方便,如下:casewhen [conditional test 1] then [result 1]when [conditional test 2] then [result 2]else [default result]end这种条件下,返回的结果取决于相应的条件测试是否为真。示例:mysql>select case 'green' when 'red' then 'stop' when 'green' then 'go' end;select case 9 when 1 then 'a' when 2 then 'b' else 'n/a' end;select case when (2+2)=4 then 'ok' when(2+2)<>4 then 'not ok' end asstatus;select name,if((isactive = 1),'已激活','未激活') as result fromuserlogininfo;select fname,lname,(math+sci+lit) as total,case when (math+sci+lit) < 50 then 'd'when (math+sci+lit) between 50 and 150 then 'c'when (math+sci+lit) between 151 and 250 then 'b'else 'a' endas grade from marks;select if(encrypt('sue','ts')=upass,'allow','deny') as loginresultfrom users where uname = 'sue';#一个登陆验证七、格式化函数date_format(date,fmt) 依照字符串fmt格式化日期date值format(x,y) 把x格式化为以逗号隔开的数字序列,y是结果的小数位数inet_aton(ip) 返回ip地址的数字表示inet_ntoa(num) 返回数字所代表的ip地址time_format(time,fmt) 依照字符串fmt格式化时间time值其中最简单的是format()函数,它可以把大的数值格式化为以逗号间隔的易读的序列。示例:select format(34234.34323432,3);select date_format(now(),'%w,%d %m %y %r');select date_format(now(),'%y-%m-%d');select date_format(19990330,'%y-%m-%d');select date_format(now(),'%h:%i %p');select inet_aton('10.122.89.47');select inet_ntoa(175790383);八、类型转化函数为了进行数据类型转化,mysql提供了cast()函数,它可以把一个值转化为指定的数据类型。类型有:binary,char,date,time,datetime,signed,unsigned示例:select cast(now() as signed integer),curdate()+0;select 'f'=binary 'f','f'=cast('f' as binary);九、系统信息函数database() 返回当前数据库名benchmark(count,expr) 将表达式expr重复运行count次connection_id() 返回当前客户的连接idfound_rows() 返回最后一个select查询进行检索的总行数user()或system_user() 返回当前登陆用户名version() 返回mysql服务器的版本示例:select database(),version(),user();selectbenchmark(9999999,log(rand()*pi()));#该例中,mysql计算log(rand()*pi())表达式9999999次。
本文转自农夫山泉别墅博客园博客,原文链接:http://www.cnblogs.com/yaowen/p/8118049.html,如需转载请自行联系原作者