MySQL基本语句
數(shù)據(jù)庫語句介紹:
語言分類:
DDL:數(shù)據(jù)庫和表
DML:表中的數(shù)據(jù)
DQL:查詢表中的數(shù)據(jù)
DCL:(授權(quán))
DDL:
1、操作數(shù)據(jù)庫
創(chuàng)建數(shù)據(jù)庫:
create database 數(shù)據(jù)庫名;
創(chuàng)建數(shù)據(jù)庫,判斷是否存在,如果不存在再創(chuàng)建:
create database if not exists 數(shù)據(jù)庫名;
創(chuàng)建數(shù)據(jù)庫,并指定字符集:
create database 數(shù)據(jù)庫名 character set 字符集名
查看所有數(shù)據(jù)庫:
show databases;
查看數(shù)據(jù)庫創(chuàng)建語句:
show create database 數(shù)據(jù)庫名;
切換數(shù)據(jù)庫:
use 數(shù)據(jù)庫名;
修改數(shù)據(jù)庫字符集:
alter database 數(shù)據(jù)庫名 character set utf8;
刪除數(shù)據(jù)庫:
drop database 數(shù)據(jù)庫名;
drop database if exists 數(shù)據(jù)庫名;
2、操作表
創(chuàng)建表:
create table 表名(
列名1 類型1,
列名2 類型2,
列名3 類型3);
mysql數(shù)據(jù)類型:
1、int:整數(shù)類型
2、double:小數(shù)類型
3、date:日期(yyyy-MM-dd)
4、datetime:日期(yyyy-MM-dd HH:mm:ss)
5、datestamp:時間戳類型(yyyy-MM-dd HH:mm:ss)
注意:如果不給時間戳賦值或者賦值為null 那么它會默認獲取當前時間
6、varchar:字符串
復制表:
create table 表名 like 被復制的表名;
查看表結(jié)構(gòu):
desc student;
查看所有表:
show tables;
修改表名:
alter table student rename to stu;
修該表的字符集:
alter table student character set 字符集;
添加一列:
alter table 表名 add 列名 數(shù)據(jù)類型;
修改列名:
alter table stu change 原列名 新列名 新數(shù)據(jù)類型;
alter table stu modify 列名 新數(shù)據(jù)類型;
刪除列:
alter table stu drop 列名;
刪除表:
drop table 表名;
drop table if exists 表名;
DML:表中的數(shù)據(jù)
1、添加數(shù)據(jù):
insert into 表名(列名1,列名2,列名3……)values(值1,值2,值3……);
注意:列名和值要一一對應
insert into 表名 values(值1,值2,值3……);
注意:如果不寫列名 ,那么默認就是添加所有
除了數(shù)字類型,其他類型需要用引號(單雙都是可以的)引起來;
一次性添加多行數(shù)據(jù):
insert into stu values(2,'dodo',15),(3,'hoho',45),(5,'roro',25);
查詢所有:select * from stu;
2、刪除數(shù)據(jù)
delete from 表名 where 條件
注意:如果不加條件,刪除表中所有的數(shù)據(jù)
3、刪除全部數(shù)據(jù):
1、delete from 表名; (效率低,不推薦使用)一條一條的刪除(數(shù)據(jù))
2、truncate table 表名; (效率高 推薦使用) 直接把表刪除 然后再重寫創(chuàng)建一張表
4、修改:
update 表名 set 列名1 = 值1,列2 = 值2 where 條件;
注意:如果不加條件 就會修改表中所有的數(shù)據(jù)
DQL:查詢數(shù)據(jù)
基礎查詢:
查詢所有:
select * from 表名;
根據(jù)條件查詢:
select * from 表名 where 條件
查詢某一列數(shù)據(jù):
select 列名 from 表名 where 條件
ifnull(表達式1,表達式2);
表達式1:哪個字段需要判斷是否為空
表達式2:如果為空,就替換成該值
select id,stu_name,ifnull(age,0) from stu where id = 2;
as:起別名 as可省略
select id,stu_name,ifnull(age,0) age from stu where id = 2;
條件查詢:
1、where子句后跟條件
2、運算符
<,>,<=,>=,<>(不等于)
select * from stu where id <> 2;
between and :在兩者之間 (包含兩頭)
select * from stu where id between 2 and 5;
in:集合
select * from stu where id in(2,3,5);
like:模糊查詢
占位符
_:一個字符
select * from stu where stu_name like 'ho_o';
%:多個字符
select * from stu where stu_name like '%o';
is null:
select * from stu where age is null;
and / &&:
or /||:
not / !:
轉(zhuǎn)載于:https://www.cnblogs.com/wen0223/p/10810832.html
總結(jié)
- 上一篇: Codeforces Round #55
- 下一篇: mysql开发认证 cmdev_学无止境