安装
yum - y install mysql-servse
启动mysql服务
service mysqld start
运行端口为3306
登陆
mysql -uroot
语法 :mysql -u账号 -p密码
默认是空密码
库和表
层次关系
库-->表
create database 库名;创建一个库
show database;查看有哪些库
use 库名;进入这个库
show tables;查看表
创建表
CREATE TABLE fruits(
f_id CHAR(10) PRIMARY KEY,
s_id INT NOT NULL,
f_name char(255) NOT NULL,
f_price DECIMAL(8,2) NOT NULL,
);
语法 CREATE TABLE 表名(
列名 类型,约束条件,
);
后面要用,隔开
内容如图所示
f_id | s_id | f_name | f_price |
---|
添加数据
INSERT INTO fruits(f_id,s_id,f_name,f_price) VALUES('a1',101,'apple',5.2);
INSERT INTO fruits(f_id,s_id,f_name,f_price)VALUES('b1',101,'blackberry',10.2);
INSERT INTO fruits(f_id,s_id,f_name,f_price) VALUES('bs1',102,'orange',11.2);
INSERT INTO fruits(f_id,s_id,f_name,f_price) VALUES('bs2',105,'melon',8.2);
INSERT INTO fruits(f_id,s_id,f_name,f_price) VALUES('t1',102,'banana',10.3);
INSERT INTO fruits(f_id,s_id,f_name,f_price) VALUES('t2',102,'grape', 5.3);
INSERT INTO fruits(f_id,s_id,f_name,f_price) VALUES('o2',103,'coconut',9.2);
INSERT INTO fruits(f_id,s_id,f_name,f_price) VALUES('c0',101,'cherry',3.2);
INSERT INTO fruits(f_id,s_id,f_name,f_price) VALUES('a2',103,'apricot',2.2);
INSERT INTO fruits(f_id,s_id,f_name,f_price) VALUES('l2',104,'lemon',6.4);
格式:
INSERT INTO 表名(列1,列2,列3) VALUES(值1,值2,值3);
如果值的类型是字符型需要加引号。
更新表
uodate fruits set f_name='sss' where s_id=‘101’ ;
删除表
delete from fruits where s_id=‘102’;
查询(以刚才创建的表为例)
查询所有字段
select * from fruits
查询制定字段
select * from fruits where f_name='apple'
带IN关键字查询
IN(aa,bb)满足条件范围内的一个值即可匹配。
select * from fruits where f_name IN ('apple‘,’orange‘)
between and 范围查询用法
select * from fruits where f_price between 5 and 15;
查询价格在5到15之间的全部信息
空值查询
SELECT * FROM 表名 WHERE 字段名 IS NULL;
//查询字段名是NULL的记录
SELECT * FROM 表名 WHERE 字段名 IS NOT NULL;
//查询字段名不是NULL的记录
带AND的多条件查询
selcet * from fruits where s_id=101 and f_price>5;
带or的多条件查询
selcet * from fruits where s_id=101 or f_price>5;
关键字DISTINCT(查询结果不重复)
select distinct s_id from fruits;
对查询结果排序(order by)
select distinct s_id from fruits order by s_id;
通过s_id进行排序,默认升序
select distinct s_id from fruits order by s_id desc;
降序排列
分组查询(group by)
s_id,count(f_name),group_concat(f_name) from fruits group by s_id;
对分组过后的结果可以进行having过滤
select s_id,count(f_name),group_concat(f_name)
from fruits group by s_id having count(f_name) > 1
limit限制查询结果的数量
select * from fruits limit 4;
集合函数查询
select conut(*) from fruits;
select SUM(f_price)from fruits;
select AVG(f_price)from fruits;
select MAX(f_price)from fruits;
select MIN(f_price)from fruits;
多表查询
select s.s_id,s.s_name,f.f_name,f.f_id
from 表一 as s ,表二 as f
where f.s_id = s.s_id
//fruits 和suppliers为表名
表一用s表示,表二用f表示
内连查询inner join表名 on 连接条件
select s.s_id,s.s_name,f.f_name,f.f_id
from 表一 as s INER JOIN表二 as f
ON f.s_id = s.s_id