mysql入门教程
步骤
- 启动服务 shell> mysqld
- 客户端 shell> mysql --help
- 客户端登录 mysql -u root -p
如果服务器在另一台计算机 需要ip地址和端口参数 mysql -h 127.0.0.1 -P 3306 -u root -p
登录时指定要操作哪个数据库 mysql -u root -p 库名 - 执行各种sql
sql
- select version(), current_date();
关键字大小写都行,函数可以省略(),每句分号结尾。 - create datebase 库名;
刚连接mysql后,mysql只有几个保存系统信息的内置数据库(表信息 权限信息)我们不应该所以动内置库。schema是逻辑上的大分块,schema下包含库。当有一个项目想保存信息时,我们需要先新建一个库 database,然后在database下新建表,表里存信息。有些数据库中schema和database一样。
比喻mysql是物流港一块千亩地皮,schema是划分的大区域 物流一区物流二区,database是物流一区里一个厂房仓库,table是厂房里的一个个房间,table里的数据是小房间里的货物。 - use 库名 ;
切换数据库。否则跨数据库查询需要跟命名空间。 - show tables; 查看库下所有表
- describe table; 查看表字段定义
出现的问题
- 有同学sqlite数据库文件和mysql数据库文件混淆,它们的数据库存储方式和数据存储位置不同。
select * from menagerie.pet;
create database test;
show tables;
create table shop (
article int(4) unsigned zerofill default '0000' NOT NULL,
dealer char(20) default '' not null,
price double(16, 2) default '0.00' not null,
primary key(article, dealer)
);
insert into shop values (1, 'A', 3.45), (2, 'B', 3.99), (3, 'B', 1.45),
(3, 'C', 1.69), (3, 'D', 1.25), (4,'D',19.95);
select * from shop;
select Max(article) as max_article from shop;
select article, dealer from shop
where price = (select max(price) from shop);
select min(price) from shop where article=3;
select min(price) from shop where article=1;
select article, min(price) as price from shop group by article;
CREATE TABLE person(
id int primary key auto_increment,
name varchar(20) not null
);
create table shirt(
id int primary key auto_increment,
style varchar(20) not null,
color varchar(20) not null,
person_id int references person.id
);
insert into person values (null, '小明');
insert into person values (null, '小红');
insert into shirt values (null, '短袖', '蓝', 1), (null, '外套', '棕', 1), (null, '风衣', '黑', 1);
insert into shirt values (null, '短袖', '蓝', 2), (null, '外套', '粉', 2), (null, '裙子', '红', 2);
select * from person;
select * from shirt;
show create table shirt;
select p.name, s.style, s.color from person as p
inner join shirt s on p.id = s.person_id
where s.color = '粉' and s.style='外套';