维护网站,经常操作数据库,使用sql语句可以达到事半功倍的效果。比如,把所有密码为空的教师初始设成id一致,sql语句比手动快万倍。
下面介绍数据库开发中经常用到的一些sql语句:
一 建库操作
1.创建数据库并编码utf8: CREATE DATABASE IF NOT EXISTS test DEFAULT CHARACTER SET 'utf8'
2.删除数据库test: DROP DATABASE test
3.显示数据库: SHOW DATABASES
4.增加新用户和密码: CREATE USER test IDENTIFIED by '123'
5.查看编码: SHOW VARIABLES WHERE variable_name like 'character%' (character_set_client和character_set_connection一致utf8则无乱码)
二 建表操作
1.创建主键自增长的学生表(若表明为order关键字,需返单引号括起来``):
create table if not exists user(
id int unsigned not null auto_increment,
username varchar(50) not null,
password varchar(50) not null,
regtime int not null,
admin tinyint not null,
primary key(id)
);
2.创建有外键依赖的课程表:
create table A
(
BookID varchar(10) primary key
);
create table B
(
BookID varchar(10),
BookName varchar(81),
primary key (BookID,BookName),
foreign key (BookID) references A(BookID)
);
3.更改表结构: ALTER TABLE user ADD COLUMN score NUMERIC(4,2);
4.增加主键: ALTER TABLE user ADD CONSTRIANT sj_pk PRIMARY KEY(id,username);
5.增加外键: ALTER TABLE cars ADD CONSTRIANT sj_fk FOREIGN KEY(userid) REFERENCES user(id);
三 表的增删改查CRUD
1.增: INSERT INTO user(password,username) VALUES(123,'rose')
2删: DELETE FROM user WHERE username='rose'
3改: UPDATE user set password=123 where username='rose';
4查: SELECT * FROM `user` ORDER BY id;
空值查询: SELECT * FROM `user` WHERE username IS NULL;
句式: SELECT * FROM +WHERE +ORDER BY + GROUP BY + HAVING
四 视图操作(视图中的字段就是来自一个或多个数据库中的真实的表中的字段)
1.创建视图:
CREATE VIEW
[Products Above Average Price]AS
SELECT
ProductName,UnitPriceFROM
ProductsWHERE
UnitPrice>(SELECT AVG(UnitPrice) FROM Products)
2.查询视图:
SELECT
*FROM
[Category Sales For 1997]WHERE
CategoryName='Beverages'
3.更新视图:
SQL CREATE OR REPLACE VIEW Syntax CREATE OR REPLACE VIEW view_name AS SELECT column_name(s) FROM table_name WHERE condition
4.删除视图:
SQL DROP VIEW Syntax DROP VIEW view_name
未完待续,后续补充 分组GROUP BY; 字符串处理TRIM();distinct;exits;like模糊查询,sql注入攻击