mysql常用操作整理
對庫的操作:
建立:create database db_test1;
刪除:drop database db_test1;
查詢: show databases;
切換庫:use db_name;
對錶的操作:
建立:create table tb_name (col_name col_type [not null | null] ,col_name2,col_type )engine = innodb default charset = utf8;
create table a(a int(10),b varchar(10),c char(10) not null)engine = innodb default charset = utf8;
檢視基本表結構:desc tb_name;
檢視建表語句: show create table tb_name
表結構操作:
增列: alter table student add column age int(3);
刪列: alter table a drop column b;改列: alter table student modify id int(11) unsigned auto_increment;
重新命名: alter table student change id s_id int(5);
對記錄的操作:插入一條:
insert into tb_name(col_name ,col_name) values('1','b'); 或者 insert into a values('1','b'),('2','c');
插入多條:
insert into a(a,c) values('1','b'),('2','c');
改:
update tb_name set col_name = 100 [where col_name = 1] ;
關聯更新:update student s,city c set s.city_name = c.name where s.city_code = c.code;
刪除:
delete from tb_name where col_name= 'b';
查詢
select * from tb_name; 查全部
select col_name from tb_name where col_name = condition 根據條件查詢指定的列
select col_name from tb_name where col_name = '小明' and col_code = '123' ,多條件並且查詢;
select col_name from tb_name where col_name = '小明' and col_code = '123'or col_age =18 , 滿足小明和123記錄 或者是 18的記錄都符合
select col_name from tb_name where id = 1 order by id [asc|desc] limit 10; 根據id排序 asc 升序 desc 降序
限制條數limit 10 = limit 0,10
語法:limit offset,num offset 偏移量 num 查詢條數
用途:分頁演算法
offset = (請求的頁碼數 - 1) * 此頁顯示的條數 num = 此頁顯示的條數
between.. and 操作符例項
會選取介於兩個值之間的資料範圍。這些值可以是數值、文字或者日期。
SELECT column_name(s)FROM table_name WHERE column_name BETWEEN value1 AND value2
in 操作符例項
如果我們希望從上表中選取姓氏為 Adams 和 Carter 的人:我們可以使用下面的 SELECT 語句:
SELECT * FROM Persons WHERE LastName IN ('Adams','Carter')