1. 程式人生 > >MySQL操作基本語法

MySQL操作基本語法

建立表:

create table student(
	id number(8) primary key not null,
	name varchar(20) not null,
	address varchar2(50) default '地址不詳'
);

插入資料:

insert into student(id,name) values(111,'名字');

刪除資料:

delete from student where id=111;

更新資料:

update student set name='名字' where name='姓名';

查詢資料:

select * from student;

新增新列:

alter table student add(sex varchars(4));

新增約束

alter table student add constraint ck_student_sex check(sex='男' OR sex='女');

新增外來鍵約束:

alter table stu1 add constraint fk_stu1_id foreign key(id) references stu2(id);

刪除約束

ALTER TABLE INFOS DROP CONSTRAINT CK_INFOS_UNIQUE;

修改資料型別:

alter table student modify(id number(4));

修改列名:

alter table student rename column sex to gender;

刪除列:

alter table student drop column gender;

修改表名:

alter table newstudent rename to student;

模糊查詢:

select * from student where sname like '張_%';

建立序列用於資料自增長:

create sequence myclass_id;	使用:myclass_id.nextval

增長步:

alter sequence myclass_id increment by 1;

刪除序列:

drop sequence myclass_id;

通過查詢從已有表建立另一個表:

create table 表名 as select <query>;

定義註冊使用者的儲存過程

DELIMITER $$
CREATE  PROCEDURE  register(IN  userName  VARCHAR(20),IN userPass  VARCHAR(20),OUT  userId INT)
BEGIN
INSERT INTO UserInfo(userName,userPass)VALUES(userName,userPass);
SELECT LAST_INSERT_ID() INTO userId;
END $$

使用觸發器實現使用者註冊業務

DELIMITER $$
CREATE TRIGGER tr_ register AFTER INSERT ON userinfo FOR EACH ROW 
BEGIN
IN
SERT INTO userdetails(id) VALUES(NEW.id);
END $$;