mysql必知必会——常用mysql基础语句

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/N1neDing/article/details/83279824

连接、查看数据库:

sudo mysql
show databases;
use learn;
show tables from learn;返回所有表
show columns from customers;返回所有列的属性
describe customers;同show columns
show grants;用来显示授予用户的安全权限

检索数据:

select distinct vend_id from products;
distinct用于显示不同的行,同样值的行将不显示,注意:distinct不能只针对于一个列,将被应用于所有被选择的列,只有一个列相同仍旧会被选择
select vend_id from products limit 5;
limit用于只显示前面n行
select vend_id from products limit 5,5;
5,5意为从第5行之后(即第6行)开始的5行
select vend_id from products limit 2 offset 4;
意为从第5行开始的2行

select products.vend_id from learn.products;
同时使用表名和列字

排序:

select prod_id,prod_price,prod_name from products order by prod_price,prod_name;
多个列排序,先对第一个列排序,当第一个列相同时,才按照第二个列排序
select prod_id,prod_price,prod_name from products order by prod_price desc,prod_name;
desc,asc只对前面的列进行相应排序,默认按照升序(不加),如果想对多个列进行降序,只能在每个列后加上desc
select prod_id as id,prod_price as price from products order by prod_price desc limit 1;
选择按照降序排列的第一位数据,order by需要位于from子句之后,limit子句需要位于order by子句之后

过滤数据:

select cust_email from customers where cust_email is null;
is null条件判断某一记录列的值是否为空
select prod_id,vend_id from products where prod_id = 'ANV01' or vend_id = 1003;
or返回任一列满足条件的记录
select prod_name,prod_price from products where vend_id = 1002 or vend_id = 1003 and prod_price >= 10;
and的优先级高于or的优先级,所以此语句会优先操作and左右的两个语句,并将结果返回与or左边的语句进行判断,所以返回的结果是id=1002或者 id=1003且大于10的数据,结果中包含id=1002但是价格小于10的记录,为了避免出现错误,应用圆括号将需要组合的条件括在一起,因为括号具有比and>和or更高的优先级
select prod_name,prod_price from products where (vend_id = 1002 or vend_id = 1003) and prod_price >= 10;
select * from products where vend_id in (1002,1003,1005);
in操作符,功能与or功能相同,选择括号中任一匹配条件
select * from products where vend_id not in (1002,1003);
not操作符,对后方的判断条件取反
select * from products where prod_name like '%jet%';
%表示任意字符出现任意次数(0次)
select * from products where prod_name like '_ ton anvil';
_表示该位置可以为任何字符

正则表达式:

select * from products where vend_id regexp '1001';
regexp表示后方使用正则表达式,对于正则表达式,如果匹配字符在列中出现,则返回,不需要整个串全部匹配
mysql中正则表达式不区分大小写,为区分大小写,需要使用binary关键字,如:where prod_name regexp binary 'Je';
.表示任一字符
|表示或者,相当于or
select * from products where prod_name regexp '[12] ton';
[12]内部元素表示或,相当于[1|2]
^作用之1:表示否定,[^12]表示匹配除这些字符外的任何东西(注意:如果包含了1或2,但是有其余字符,则也会被匹配)
select * from products where prod_name regexp '[1-5] ton';
[1-5]表示范围内的匹配
select * from vendors where vend_name regexp '\\.';
\\转义符,表示查找.这个符号
*表示前一个字符有0个或多个匹配
+表示前一个字符有1个或多个匹配
?表示前一个字符有0个或1个匹配
{n} 指定数目的匹配
{n,} 不少于指定数目的匹配
{n,m} 匹配范围内的数目

select * from products where prod_name regexp 's+';
[:alnum:]任意字母和数字
[:digit:]任意数字
[:lower:][:upper:]任意小写字母,任意大写字母
select * from products where prod_name regexp '0{3}';
表示匹配出现3次0
select * from products where prod_name regexp '[[:digit:]]{3}';
表示匹配连续出现3次数字的记录
^表示文本的开始
$表示文本的结尾

select * from products where prod_name regexp '^[0-9\\.]';
表示匹配首字母为数字或者小数点的记录([]中表示或者)

like和regexp的区别在like匹配整个字符串,regexp匹配子串,利用定位符^和$开始和结尾,则regexp和like作用相同

创建计算字段:

select concat(vend_name,'(',vend_country,')') from vendors;
concat()拼接串,每个串之间用逗号分隔
select rtrim(vend_name) from vendors;
rtrim去掉数据右侧多余的空格,ltrim去掉数据左边的空格,trim去掉串左右两边的空格
select prod_id,item_price,quantity,item_price*quantity as total_price from orderitems where order_num = 20005;
使用+-*/进行计算

函数:

字符串函数:
select vend_name,upper(vend_name) as BIG from vendors;
upper lower:将字符串全部转换成大、小写字母
ltrim rtrim trim:去掉串左边、右边、左右两边的空格
left right:返回串左右两边的字符
length:返回串的长度
locate:找出串的一个子串,返回子串第一次出现的位置
substring:返回子串的字符substring(str, pos)substring(str, pos, length)说明:substring(被截取字段,从第几位开始截取)
substring(被截取字段,从第几位开始截取,截取长度)
select substring(content,5) as abstract from my_content_t
select substring(content,5,200) as abstract from my_content_t
soundex:返回串的soundex值,返回语音相似的记录
select * from vendors where soundex(vend_state) = soundex('me');
soundex('me')返回了记录中发音相似的‘mi’的记录
日期函数:
now:返回当前日期和时间
date:返回时间的日期部分(年月日)
time:返回时间的时间部分(时分秒)
dayofweek:返回对应日期是星期几
select * from orders where order_date = '2005-09-12';
当日期时分秒不为00:00:00时,即使日期正确,也不会返回
select * from orders where date(order_date) = '2005-09-01';
select * from orders where time(order_date) = '00:00:00';
year month day:返回日期中的年份、月份、日
hour minute second:返回时间的小时、分钟、秒
select * from orders where date(order_date) between '2005-09-01' and '2005-09-30';
select * from orders where year(order_date) = 2005 and month(order_date) = 9;
以上两句均可以返回2005年9月份的订单
curdate curtime:返回当前日期、时间
datediff:计算两个日期之差
select datediff(curdate(),'2005-06-02');
返回今天和之后日期的相差天数
timediff:计算时间之差(小时分钟秒)
select timediff(now(),'2018-10-17 00:00:00');
数值处理函数
abs:绝对值
exp:一个数的指数
cos sin tan:正余弦正切
mod:余数
rand:随机数
sqrt:数的平方根
聚集函数:
avg:返回某列的平均值
count:返回某列的行数,用于确定符合条件记录的数目
max:返回某列的最大值,可用于返回最大日期数
min:返回某列的最小值
sum:返回某列值之和
select sum(orderitems.quantity*orderitems.item_price) as allmoney from orderitems;
返回总的订单金额

数据分组:

group by:分组,子句可以包含多个列,select中的每个列需要在group by子句中给出,出现在where子句之后,order by子句之前
select vend_id,count(*) as number from products group by vend_id;
having:类似于where,但是having可用于过滤分组,where只用于过滤行;where在分组前过滤,having在分组后过滤
select vend_id,count(*) from products where prod_price > 5 group by vend_id having count(*) > 2;
一般使用count时,都需要进行分组

select子句顺序:
select
from
where
group by
having
order by
limit

使用子查询:

select cust_id from orders where order_num in (select order_num from orderitems where prod_id = 'TNT2');
子查询一般与in操作符结合使用
select cust_name,cust_state,(select count(*) from orders where orders.cust_id = customers.cust_id) as number from customers order by cust_id;

联结:

内部联结:
select vend_name,prod_name,prod_price from vendors inner join products on vendors.vend_id = products.vend_id;
from A inner join B on 条件
select prod_name,vend_name from orderitems,products,vendors where products.vend_id = vendors.vend_id and orderitems.prod_id = products.prod_id and order_num = 20005;
联结的表越多,性能下降的越厉害
as给表起别名:
select cust_name from customers as c where c.cust_name regexp '^C';
自联结:使用多个相同的表,取不同的别名进行联结
select p1.prod_id,p1.vend_id,p1.prod_name from products as p1,products as p2 where p1.vend_id = p2.vend_id and p2.prod_id = 'DTNTR';
一般自联结比子查询要快很多
外部联结:
select cust_name,customers.cust_id,order_num from customers left outer join orders on customers.cust_id = orders.cust_id;
左外联结:from A left outer join B on A.a = B.a选择左边表所有的行,以及右边表对应的行
右外联结:from A right outer join B on 选择右边表所有的行,以及左边表对应的行
union:由两条或两条以上的select语句组成,语句之间用union分隔
查询必须包含相同的列、表达式或聚集函数
union会自动取消重复的行,但是unoin all不会取消重复的行,同一行可能出现多次
对于union使用排序时,在最后一个查询后加上order by

数据插入:

insert into customers(cust_name,cust_address,cust_city,cust_state,cust_zip,cust_country) values('A','B','C','D','E','F');
可以不再表名后加类型,但是加了后会更加安全,不需要插入的列的值可设为NULL或插入时不填写列名和对应的value值(将使用定义的默认值,如果未设置默认值,将产生错误信息)
插入多行语句:insert into table(……)values(……),(……)
insert into customers(cust_name,cust_address,cust_city,cust_state,cust_zip,cust_country) values('A','B','C','D','E','F'),('A','A','A','A','A','A');
插入检索出的数据:
insert select,例如将一个表检索出插入另一个表,也可以使用where过滤插入的数据
insert into customers(cust_name,cust_address) select order_num,cust_id from orders where cust_id = 10001;

更新数据:

update set where
update customers set cust_email = "[email protected]" where cust_id = 10005;
update customers set cust_name = "fanjiuding",cust_email = "1394754501" where cust_id = 10005;
更新多列,用逗号隔开
ignore:如果更新时出现错误,则整个更新会取消,使用update ignore customers时,即使发生错误,也会继续更新
为了删除某个列的值,可以将其设为NULL:update ignore customers set cust_name = NULL,cust_email = "1394754501" where cust_id = 10005;
delete:删除行,如果删除列,可以使用update不添加where条件
delete from customers where cust_id = 10018;
delete删除表的行或所有行,但不删除表本身
truncatetruncate table语句可以从表中删除所有行,相对于delete更快,因为它是删除原来的表并重新创建一个表,而不是逐行删除表中的数据

创建和操纵表:

create table test
     (key1 int not null,
     key2 char(50) null,
     key3 char(10) not null,
     primary key (key1));
create创建表名,列名和类型,声明
每个列或者为null或者为not null,允许null值的列允许在插入时不给出该列的值,不允许null的列在插入或更新时该列必须有值
主键值必须唯一,即单个主键值或者多个列组成的主键组合必须唯一,且不能为null
primary key声明主键在最后,创建多个列组成的主键,应当为:primary key(order_num,order_item)
auto_increment:每个表允许一个auto_increment列,而且它必须被索引(通过使它成为主键),作用为每次插入数据时自动增加1
create table test1 (key1 int not null auto_increment, key2 char(50) not null, key3 char(10) not null, primary key (key1,key2));
对于auto_increment的值,也可以显示声明为具体的值,则之后的插入记录如果未声明,则在前一个的记录基础上+1
default:当插入行没有给出值时,允许指定默认值
create table test2 (key1 int not null auto_increment, key2 char(50) not null default '1', key3 char(10) not null, primary key (key1));
alter:更新表
alter table vendors add vend_phone char(20);
添加一个列
alter table vendors drop column vend_phone;
删除一个列
alter table orderitems
      add constraint fk_orderitems_orders
      foreign key (order_num) references orders (order_num);
创建外键
drop:删除表
drop table test;
rename:重命名表
rename table test1 to testagain;
可以同时对多个表进行重命名:rename table a to b,c to d,e to f;

视图:

create view:创建视图
drop view:删除视图
更新视图时,可使用drop然后create,也可以直接用create or replace view(有则替换,没有则创建)
create view customerorder as select cust_name,cust_contact from customers,orders where customers.cust_id = orders.cust_id;
select * from customerorder;
创建视图后,可以重复使用,简化复杂的sql操作

触发器:

在表发生更改时(delete insert update)自动处理。

事务:

指一组sql语句
事务处理:一组操作为整体执行,或者完全执行,或者发生错误,进行回退以完全不执行

作为两种常用的引擎,myisam不支持明确的事务处理管理,innodb支持事务管理
start transaction:表示事务的开始
rollback:回退
select * from testagain;start transaction;delete from testagain;select * from testagain;rollback;select * from testagain;
最后因为回退了,所以数据未改变
commit:事务处理块中,提交不会像其他sql语句一样自动隐含提交,commit可进行明确的提交
start transaction;delete from testagain where key1 = 4;delete from testagain where key1 = 7;commit;
savepoint delete1;设置保留点,回退时可以回退到保留点的位置
rollback to delete1;

创建用户账号:

create user ding identified by '123456';用户名ding,password:1223456
select user from user; 可查看所有用户
rename user ding to ding1;
drop user ding1; 删除用户及其权限
show grants for ding;查看一个用户的权限,usage on *.*表示没有权限
grant select,insert on learn.* to ding;
授予权限,以上为授予在数据库上select,insert的权限,learn.* 表示learn数据库上的所有表
revoke select on learn.* from ding;
revoke撤销权限
grant all和revoke all对整个服务器,on database.*对整个数据库,on database.table对特定的表
set password for ding = password('aaaa'); 更改密码

猜你喜欢

转载自blog.csdn.net/N1neDing/article/details/83279824
今日推荐