1. 程式人生 > >SQL語句基本語法

SQL語句基本語法

sql

首先寫入可顯示中文代碼

set character_set_client=gbk;
set character_set_results=gbk;

或只輸一句

set names gbk;

創建數據庫

create database 庫名;

查詢現有數據局

show databases;

刪除數據庫

drop database +庫名

使用庫

use 庫名;

創建表

create table Student(
     id int,
     name varchar(20) not null,
     age int,
     sex  char(2) not null;
     major varchar(20)
);

以學生表為例,創建主鍵自增表

creat table student(
     id int primary key auto_increment,//註:只有int類型且為primary key 才可以使用auto_increment.
     name varchar(20) not null,
     banji varchar(20) not null,
     banji integer default(1),  //設定默認值為1
     );

創建表後添加設定或改變默認值

例如:

alter table student modify score int;
alter table student modify score int default ‘1‘;

主鍵約束

創建表時添加主鍵約束

creat table person(
    id int not null,
    name varchar(20) not null,
    adress varchar(50),
    primary key(id)
);

創建表後添加主鍵約束

alter table person add primary key(id);

外鍵約束

create table Score(
     p_id int,
     name varchar(20) not null,
     age int,
     sex  char(2) not null;
     major varchar(20),
     foreign key(p_id) reference persons(id)
);

創建表後添加外鍵約束:

alter table 表名 add foreign key (p_id) references 主表名 (id)

創建主外鍵關系約束

alter table score add foreign key(p_id) reference person(id);
check
banji int (banji between 1 and 3)


查詢表

show tables;

在表中添加字段(就是添加各種想要的屬性)(比如這裏在student表中添加score)

alter table student add score double;

即 alter table 表名 add 字段 字段類型;

添加完字段後可以 查詢表結構

desc Student;

即 describe 表名; 或 desc 表名;

修改表名

alter table 原表名 rename to 新表名;

修改字段名(屬性名)

alter table 表名 change 原字段名  新字段名 原數據類型;
alter table student change physics physisc char(10) not null;

//註:只有int類型且為primary key 才可以使用auto_increment.

修改屬性(即修改修飾這個字段的數據類型)

alter table student modify score int;


即alter table 表名 modify 字段名 數據類型;

刪除一列

alter table 表名 drop 字段名

刪除一條記錄

delete  from student where score<60;
delete  from student where name=xiaohong;
delete from student where name="zhangsan" and major="yingyu";

(比如表中有兩個都是zhangsan,並且沒設置id為主鍵的話id也都是1,但是兩人專業不一樣,刪除的時候就要加上兩個條件,否則同名的都會被刪除)


添加一條記錄

insert into student(id,name,age,major)values(1,‘張‘,20,80);
insert into student(id,name,age,major)values(1,"張三",20,"安卓");

(添加完可以)查看表內內容

select * from 表名  
select name from student where id=1;

多表查詢

select 表名.字段名 from 表1,表2... where 表1.字段=表2.字段 and 其它查詢條件;

修改某一個記錄(把表上id號為1這條記錄上的sex這個字段內容改為女)

update people set sex=‘女‘ where id=1

排序

select * from 表名 order by 字段名 desc;
select * from 表名 order by 字段名 asc;

修改固定詞

inser into like ‘宋_‘


SQL語句基本語法