本文共 3233 字,大约阅读时间需要 10 分钟。
确认已安装MySQL数据库环境,确保ECShop数据库已创建并连接成功。
使用以下命令连接MySQL数据库:
mysql -u [username] -p -h [host]
参数说明:
-u
:用户名-p
:密码-h
:主机地址show databases;
use [database_name];
create database [db_name] charset utf8;drop database [db_name];
desc [table_name];
show create table [table_name];
create table [table_name] ( [字段名] [字段类型] [参数] ...) engine=innodb charset=utf8;
alter table [table_name] add [column_name] [type] [参数];
alter table [table_name] change [旧名] [新名] [type] [参数];
alter table [table_name] drop column [column_name];
alter table [table_name] add primary key ([主键列名]);
alter table [table_name] drop primary key;
insert into [table_name] ([列名1], [列名2] ...) values (值1, 值2 ...);
update [table_name] set [列名] = 值 where 条件;
delete from [table_name] where 条件;
查询基础语法:
select [列名] from [table_name] where 条件;
复杂查询:
select max([列名]) from [table_name];
select * from [table_name] order by [列名] desc limit n;
left join tableA on [条件];right join tableB on [条件];inner join tableC on [条件];
select * from [tableA] where [条件] = (select [列名] from [tableB] where [条件]);
select * from (select * from [tableA]) as [alias];
创建触发器:
create trigger [trigger_name] after|before [事件] on [table_name] for each row [触发语句];
删除触发器:
drop trigger [trigger_name];
innodb
:支持事务,适合高并发myisam
:速度快,不支持事务set names utf8;
start transaction;
commit;rollback;
创建数据库并建立表:
create database shop charset utf8;use shop;create table goods ( goods_id int auto_increment, goods_name varchar(20) not null, cat_id int, brand_id int, goods_sn varchar(50), goods_number int, shop_price decimal(10,2), click_count int default 0) engine=innodb charset=utf8;
插入数据:
insert into goods (goods_name, cat_id, brand_id, goods_sn, goods_number, shop_price, click_count) values ('KD876', 4, 8, 'ECS000000', 10, 1388.00, 7),('诺基亚N85原装充电器', 8, 1, 'ECS000004', 17, 58.00, 0),('诺基亚原装5800耳机', 8, 1, 'ECS000002', 24, 68.00, 3),...
执行完毕后,进行索引优化:
alter table goods add index idx_goods_name (goods_name);alter table goods add index idx_shop_price (shop_price);alter table goods add index idx_click_count (click_count);alter table goods drop index idx_goods_name;
select goods_id, goods_name, shop_price from goods where goods_id = 32;
select cat_id, max(shop_price) from goods group by cat_id;
select name, sum(score < 60) as gk, avg(score) as pj from stu group by name having gk >= 2;
select * from goods order by shop_price desc limit 3;
select goods_name, cat_name, shop_price from goods left join category on goods.cat_id = category.cat_id;
select id, sum(num) from (select * from ta union all select * from tb) group by id;
创建触发器:
create trigger tg_goods_update after update on goods for each rowupdate other_table set field = new.field where id = new.id;
以上内容涵盖了MySQL的基础操作和高级功能,适合用于技术复习和实际项目中的应用。
转载地址:http://eadfk.baihongyu.com/