本文共 2378 字,大约阅读时间需要 7 分钟。
MySQL作为一款流行的关系型数据库管理系统,广泛应用于各类企业级系统开发、数据存储和处理中。本文将从基础概念、查询操作、数据处理等多个方面,详细介绍MySQL的核心功能和使用方法。
MySQL的逻辑架构分为两个主要层次:服务层和存储引擎层。服务层负责接收客户端的查询请求、 parsing 和执行,主要包括连接管理、事务处理、缓存等功能。存储引擎则负责实际的数据存取和修改操作,常见的存储引擎有InnoDB、MyISAM等,其中InnoDB是推荐的主流引擎支持事务处理。
mysql -h host -u username -p
use database_name
show databases
show tables
show columns from table_name
show status
select [columns] from table_name [where conditions] [group by columns] [having conditions] [order by columns] [limit offset, count];
升序/降序排序:
select * from goods order by num desc;
限制返回行数:
select * from goods limit 2;
可以指定从某一行开始:
select * from goods limit 2, 2;
基本过滤:
select id, name from goods where num > 10;
复合过滤:
select * from goods where id = 2 and num > 10;
范围查询:
select * from goods where num between 5 and 10;
匹配空值:
select * from goods where num is null;
AVG():计算某列的平均值。
COUNT():统计某列的行数。
MAX()/MIN():找出某列的最大值或最小值。
SUM():计算某列的总和。
分组查询:
select num, count(num) from goods group by num;
按条件分组:
select num, count(*) from goods group by num having count(num) > 5;
select v.vend_name, p.prod_name from vendors v inner join products p on v.vend_id = p.vend_id;
select v.vend_name, p.prod_name from vendors v natural join products p on v.vend_id;
select c.cust_id, o.order_num from customers c left outer join orders o on c.cust_id = o.cust_id;
create view top_products as select * from products where num > 5;
select * from top_products;
update top_products set num = num + 1 where name = '苹果';
insert into goods (name, num) values('香蕉', 3);
update goods set num = 1 where name = '苹果';
delete from goods where num = 7;
create table vendors ( vend_id int not null auto_increment, vend_name char(50) not null, vend_address char(50) null default '*', vend_city char(40) null, primary key (vend_id)) engine=InnoDB;
alter table vendors add column vend_phone char(20);
drop table vendors;
事务处理:事务由存储引擎层实现,默认使用InnoDB引擎。
空值处理:使用is null
检测空值。
排序与过滤顺序:order by
必须放在where
子句之后。
性能优化:减少索引使用,避免过度使用通配符和正则表达式。
安全权限:合理分配用户权限,避免过度访问。
通过以上知识和操作指南,开发者可以更高效地使用MySQL进行数据存储和处理,充分发挥其强大功能。
转载地址:http://qhbfk.baihongyu.com/