一、對數據庫的操作
1、創建一個數據庫
普通創建>>> create database 數據庫名;
創建特定編碼格式>>>create database 數據庫名 character set utf-8;
查看數據庫的結構>>> show create database 數據庫名;
查看所有數據庫>>> show databases;
2、刪除一個數據庫
drop database 數據庫名;
3、使用一個數據庫
use 數據庫名;
查看正在使用的數據庫>>>select database();
二、對錶的操作
1、創建一張表
create table 表名(
字段名 數據類型(長度) [約束],
字段名 數據類型(長度) [約束]
); 其中[]代表可選內容
單表約束:primary key 主鍵約束,要求字段唯一、非空
unique 唯一約束,要求字段唯一
not null 非空約束,要求字段非空
2、查看錶
查看所有表>>>show tables;
查看錶結構>>> desc 表名;
3、刪除表
drop table if exists 表名;
4、修改表結構
添加一列>>>alter table 表名 add 列名 數據類型(長度) [約束];
修改一列>>>alter table 表名 modify 列名 數據類型(長度) [約束];
修改列名>>>alter tabke 表名 change 舊列名 新列名 數據類型(長度) [約束];
刪除一列>>>alter table 表名 drop 列名;
修改表名>>> rename table 舊錶名 to 新表名;
修改表的編碼方式>>> alter table 表名 character set utf-8;
查看錶編碼方式>>>show create table 表名;
三、對錶記錄進行操作
1、插入數據
只插入某些列>>>insert into 表名(列名1,列名2,列名3...) values(值1,值2,值3....);
插入全部列>>>insert into 表名 values(值1,值2,值3...);
注意點:1、列名數要與值的數目相同
2、列的順序與插入值的順序相同
3、列的數據類型與插入值的類型相同
4、插入的值不能超過最大長度
5、插入的值如果是字符串或者日期要加''(一般是單引號)
2、更改數據
update 表名 set 字段名=值,字段名=值....;
update 表名 set 字段名=值, 字段名=值... where 條件;
注意點:1、列的數據類型與值相同
2、修改的值不能超過最大長度
3、如果是字符串或者日期要加單引號
3、刪除表數據
刪除所有>>> delete from 表名;
刪除某個>>>delete from 表名 where 條件;或者truncate table 表名
區別:delete配合事務可恢復數據,id不重置;truncate會刪除表再創建一張新表,數據不可恢復並且id重置
四、查詢表數據
1、語法
select [distinct]* | 列名、列名 from 表名 [where 條件];
2、簡單查詢
1、查詢所有商品
select * from product;
2、查詢商品名和商品價格
select pname,price from product;
3、查詢所有商品使用表別名
select * from product as p; as可省略
4、查詢商品名使用列別名
select pname as product_name from product;
5、去掉重複值(按照價格)
select distinct(price) from product;
6、將所有商品價格+10進行顯示
select price+10 from product;
3、條件查詢
1、查詢商品名爲左慈的商品信息
select * from product where pname = '左慈';
2、查詢商品價格大於60的所有商品信息
select * from product where price > 60;
3、查詢商品名稱中含有“士”的商品信息
select * from product where pname like '%士%';
select * from product where pname like '_士%';>>>一個下劃線_表示一個佔位符
4、查詢商品id在(3,6,9)範圍內的所有商品信息
select * from product where pid in (3,6,9);
5、查詢id爲2或者6的商品信息
select * from product where pid = 2 or pid =6;
4、排序
1、查詢所有商品,按價格進行排序
select * from product order by price desc;>>>desc降序 asc升序
2、查詢名稱有“士”的商品並按價格降序排列
select * from product where pname like '%士%' order by price desc;
5、聚合(不統計null值)
1、獲得所有商品的價格總和
select sum(price) from product ;
2、獲得所有商品的平均價格
select avg(price) from product ;
3、獲得商品的種類總數
select count(*) from product ;
6、分組
1、根據cid字段分組,分組後統計商品個數
select cid,count(*) from product group by cid;
2、根據cid分組,分組統計每組商品平均價格,並且平均價格大於20000元
select cid,avg(price) a from product group by cid having a>20000;
7、查詢總結
select 一般在後面的內容都是要查詢的字段
from 要查詢的表
where 條件
group by 分組
having 分組後必須having而不用where
order by 排序。必須放到最後面
sum求和、avg平均、max最大值、min最小值、count數量