SQL常用語句大全


創建用戶create user ‘用戶名’@‘%’ identified by ‘密碼’    (%處填%表示遠程連接 localhost表示只能在本機登陸 也可以填ip )

賦予最高權限grant all on *.* to ‘user’@‘%’;

使更改立即生效 flush privileges;

查看當前用戶 select user() ;

查看當前數據庫 select database() ;

創建數據庫 create database [if not exist] 數據庫名

查看有哪些數據庫 show databases;

刪除數據庫 drop database [if exists] 數據庫名

創建表 create table [if not exists] 表名(

Id int,

name char(10),     ##char 定長字符

sex varchar(10)     ##varchar 不定長字符

建表實例

 1 CREATE TABLE Teacher
 2 (
 3 tNo varchar(255) NOT NULL,
 4 tName varchar(255),
 5 tSex char(1),
 6 tBirthDate date,
 7 tSalary decimal,
 8 tHairDate date,
 9 depNo varchar(255),
10 PRIMARY KEY (tNo),
11 CHECK (tSex="男" OR tSex="女")
12 );

 

查看有哪些表 show tables

查看表結構 desc 表名

           show create table 表名

刪除表 drop table 表名

表中數據的增刪改查

*增

insert into 表名 value();

insert into 表名 (id字段名) vaue();  #添加時給特定字段賦值

insert into 表名 values (),(),()…  #一次添加多條數據

insert into 表名 set 字段1 =value 字段2 =value…

*刪

delete from 表名 where 條件

*改

update 表名 set id = value where 條件;

*查

select * from 表名

查詢所有  select * from 表名

查詢單列  select 字段名 from 表名

查詢指定條件的內容  select * from 表名 where 條件

查詢時為列指定別名  select stu_id as 學號 from student

                          select stu_id as 學號,stu_name as 姓名 from student

模糊查詢         select * from student where stu_name like ‘y%’  ##(查詢以y開頭的數據)

                  select * from student where stu_name like ‘%y%’  ##(查詢含有y的數據)

查詢時排序        select * from student order by stu_id asc  (desc倒序,asc正序)

查詢時限制顯示數據的數量 select * from student limit 100(限制輸出的條數)

 

 

聚合函數       select MAX(stu_age) from student   常見函數(MAX()最大值MIN()最小值SUM()求和AVG()平均Count()統計ROUND()四舍五入

分組查詢       select dep_id as 學院代碼,count(dep_id) as 人數 from student group by dep_id;

增加條件       select dep_id as 學院代碼,count(dep_id) as 人數 from student group by dep_id having 人數 = 1;

更改表結構 

Alter table tbname modify id char not null ##更改字段類型和約束

常見約束  

not null 非空約束;

unique key 唯一約束;

primary key 主鍵約束;

auto_increment 自增長;

default xxx 默認值

Alter table tbname rename newname  ##更改表名

Alter table tbname change 字段名 newname  ##更改字段名

Alter table tbname add sex varchar(10)  ##增加字段

Alter table tbname add sex varchar(10) first\after** ##添加時設置字段添加的位置

Alter table tbname add unique key(字段名)  ##給指定字段添加鍵

Alter table tbname drop                     ##刪除字段

Alter table tbname drop key name      ##刪除鍵

表關聯

Constraint keyname foreign key(內部字段名) reference 外表名(外表字段)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM