1. 程式人生 > >MySQL——表的增刪改查

MySQL——表的增刪改查

注意:在MySQL中存放資料、保管資料最後都是為了使用,在使用的時候需要我們進行查詢,所以最重要的就是查詢。
1.增加(插入)
(1)在插入的時候資料應該與對應的資料型別相同。比如建立表的時候型別是int,而在插入的時候卻用了char,則會出錯。
(2)插入的資料範圍應該在規定的範圍內
(3)在values中列出的位置應該與被加入的列位置是對應的。
(4)字元或日期型別應該加上單引號
(5)插入控制不指定或指定為null
(6)可以隱含插入,但是要求插入的數量必須是表中全部列數
增加進階
當主鍵存在衝突的時候,可以選擇以下兩種方法進行處理
更新操作:insert into 表名(欄位列表) values(值列表) on duplicate key update 欄位=新值;
替換操作:replace into 表名(包含欄位) values (值列表);
2.更新
可以根據你的條件進行更新
update tb_name set col_name = expr1,[,col_name2=expr2 …] [where condition] [limit n]
eg:
update goods set price=300;
update goods set price =1000 where id = 100;
update使用細節:
。update 語法可以用新值更新原有表中的各列值
。set子句指示要修改哪些列和要給予哪些值
。where子句指定要更新哪些行。如果沒有where子句,則更新所有行
。where子句後面指定limit,更新限制數量的符合條件
3.刪除
delete from table [where condition]
4.複製表的結構
create table tb2_name like tb1_name;
5.複製表的資料
insert into tb2_name select * from tb1_name;
6.刪除表的資料
(1)delete from goods;---->刪除整個表的資料,但是表的結構還存在
(2)truncate table goods;---->把整個表的記錄刪除
delete和truncate兩種刪除整表的區別


。效果一樣,turncate速度更快
。delete語句不能刪除某一列的值(可以用update置null)
。使用delete語句僅刪除記錄,不能刪除表本身
在表的優化上面可以考慮他們兩個的使用來達到優化的效果
7.查詢
select * from table_name;---->對於*表示表中的所有列,查詢它的效率是非常低的
select distinct column from tab_name;---->查詢這一列去除重複的
select column as 別名 from 表;---->取別名
eg:
select * from student where name like ‘李%’---->%表示一個字元
select * from student where english>90;
select * from student where name like ‘李%’ and id >10;
查詢多個值或的關係:
select * from student where math in(89,90,78);/select * from student where math =89 or math=90 or math=78;
對於查詢、刪除、複製的應用練習

要求:刪除表中的重複記錄,重複的資料只能有一份
create table tt(id int,name varchar(30));
create table ttnew like tt;
insert into ttnew select distinct * from tt;
drop table tt;
alter table ttnew rename tt;