mysql學習3
Sql完成對錶中資料的增刪改查操作
--插入資料
insert into 表名(列名1,列名2,列名3) values(值1,值2,值3);
insert into student(sid,sname,gender,age,shengao) valuse(1,'張三','男',18,170);
簡單寫法
insert into student values(1,'張三',18,170); 如果只插入其中部分列,則不可以省略列名
--批量插入
insert into student values(1,'張三',18,170),(2,'張1',19,155),(...);
--單條插入和批量插入的效率問題
單條效率<批量插入
--插入中文字元亂碼問題
將mysql安裝路徑中的my.ini配置檔案中 第57行編碼改成gbk
--刪除記錄
delete from 表名 【where 條件】
delete from student where sid=10;
delete from student; 如果沒有指定條件會把表中資料全部刪除
delete 跟 truncate 刪除資料區別
delete:一條一條刪除表中資料
truncate:DDL 先刪除表 再重建表 (更改了表的結構)
關於刪除效率問題:具體要看錶中的資料量 量少 delete 量大 truncate
--更新表記錄
update 表名 set 列名=列的值,列名2=列的值2 【where條件】
update student set sname='張寧' where sid=1;(如果不加where限制條件,所有人都將改成張寧)
如果update 主鍵 列 必須加判定條件
--查詢表中資料
select * from student;
select 【distinct】【*】【列名,列名2】from 表名【where條件】
distinct:去除重複的資料
--商品分類:手機數碼,鞋靴箱包
1.分類的ID
2.分類名稱
3.分類描述
create table category(
cid int primary key auto_increment,
cname varchar(10),
cdesc varchar(30)
) ; 如果遇到Duplicate column name 'cname 解決辦法set names bgk;
--所有商品
insert into category values(null,'手機數碼','電子產品');
insert into category values(null,'鞋靴箱包','日用品');
insert into category values(null,'香菸酒水','奢侈品');
select * from category;
select cname ,cdesc from category;
--所有商品
1.商品ID
2.商品名稱
3.商品價格
4.生產日期
5.商品分類ID
商品跟商品分類 :所屬關係
create table product(
pid int primary key auto_increment,
pname varchar(10),
price double,
pdate timestamp,
cno int
);
insert into product values(null,'小米mix4',998,null,1);
insert into product values(null,'錘子',2898,null,1);
insert into product values(null,'阿迪',99,null,2);
insert into product values(null,'玉溪',20,null,3);
--簡單查詢
-- 查詢所有商品
select * from product;
--查詢商品名稱和商品價格
select pname ,price from product;
--別名查詢:as 關鍵字 as 關鍵字可以替換
--表別名:select p.pname,p.price from product as p;(主要是用於多表查詢)
--列別名:select pname as 商品名稱,price as 商品價格 from product; (as 可以省略)
--去掉重複的值
--查詢商品所有的價格
select price from product;
select distinct price from product; (distinct 去重)
--select運算查詢【在查詢結果上進行處理】
select * ,price *1.5 from product;
select *,price*1.5 as 折後價 from product;
--條件查詢【where關鍵字】
指定條件,確定要操作的記錄
select * from product where price > 60;
--where 後的條件寫法
<> 不等於 標準sql語法
!= 不等於 不標準sql語法
--查詢商品價格不等於88的商品
select * from product where price !=88;
--查詢商品價格在10-100之間
select * from product where price >10 and price <100;
between ... and ...
select * from product where price between 10 and 100;
--邏輯運算
and or not
select * from product where price <100 or price >900;
--like:模糊查詢
_:代表一個字元
%:代表多個字元
--查詢第二個字是米的商品
select * from product where pname like '_米%'
--查詢商品ID是 1 2 4的商品
select * from product where cno in (1,2,4);