创建数据库:create database xxx;
列出数据库:show databases;
选择数据库:use xxx;
创建数据表:create table xxx(id,state,population);
create table IF NOT EXISTS states (Id not null primary key auto_increment,state char(25),population int(9));
插入数据:
insert into xxx (id,state,population) values(null,'alabama','4822023');
创建更多记录:
insert into states(id,state,population) values (null,'xxx','xxx'),(null,'xxx','xxx');
更新表格:
UPDATE Person SET FirstName = 'Fred' WHERE LastName = 'Wilson'
查看表所有的列:
SHOW FULL COLUMNS from person;
在原有表格上添加新的表格:
注意这里创建的新表格将旧表格归为自己一部分,附在右侧```
在旧表格基础上新建空表格:
CREATE TABLE `people` ( `peopleid` smallint(6) NOT NULL AUTO_INCREMENT, `firstname` char(50) NOT NULL, `lastname` char(50) NOT NULL, `age` smallint(6) NOT NULL, `townid` smallint(6) NOT NULL, PRIMARY KEY (`peopleid`), UNIQUE KEY `unique_fname_lname`(`firstname`,`lastname`), KEY `fname_lname_age` (`firstname`,`lastname`,`age`) ) ;
删除表格:
或者是
DROP TABLE IF EXISTS XXX;```
删除行:
删除某行
DELETE FROM Person WHERE LastName = 'Wilson'
删除整个列表行
DELETE* FROM table_name```
输出全部:
>```select* FROM database``
设置AUTO_INCREMENT的起始值
>```ALTER TABLE Persons AUTO_INCREMENT=100```
进行高级命令查询:
>```SELECT state,population FROM database ORDERBY population DESC;#这里DESC是递减顺序```
返回唯一的的列表:
>```SELECT DISTINCT Company FROM ORDERS```
排序:
>```SELECT Company, OrderNumber FROM Orders ORDER BY Company DESC, OrderNumber ASC#Company逆顺序排列,OrderNumber升序排列```
限制输出数量:
>```SELECT* FROM table_name LIMIT 5```
LIKE指定模式
>```SELECT * FROM Persons WHERE City LIKE '%lon%' 选出包含lon字符的人```
通配符(必须配合着LIKE来用)
- %替代一个或多个字符
- _仅替代一个字符
- [charlist]字符列中的任何单一字符
- [^charlist]或者[!charlist]不在字符列中的任何单一字符
UNION用来合并多个SELECT结果集:
SELECT column_name(s) FROM table_name1
UNION
SELECT column_name(s) FROM table_name2
注意,UNION ALL会返回所有值,可能重复
SELECT INTO可以复制数据
SELECT LastName,Firstname
INTO Persons_backup
FROM Persons
WHERE City='Beijing'
这里顺便是select - into - from
isnull()函数返回默认值
SELECT ProductName,UnitPrice*(UnitsInStock+IFNULL(UnitsOnOrder,0))
FROM Products
判断空与非空is null/is not null
SELECT LastName,FirstName,Address FROM Persons
WHERE Address IS NOT NULL
基本运算符:
=等于
<>不等于#有些sql可以写成!=
BETWEEM在某个范围内
LINK搜索某种模式
使用WHERE语句
>```SELECT * FROM Persons WHERE City='Beijing'```
CASE WHEN语句
having sum(case when b.score>=60 then 0 else 1 end)>=2
Constraints约束:
NOT NULL
UNIQUE
PRIMARY KEY
FOREIGN KEY
CHECK
DEFAULT
CHECK限制范围
ALTER TABLE Persons
ADD CHECK (Id_P>0)
DEFAULT添加默认值
CREATE TABLE Persons
(
City varchar(255) DEFAULT 'Sandnes'
)
另外添加或者删除
ALTER TABLE Persons
ALTER City SET DEFAULT 'SANDNES' /// DROP DEFAULT
Create index添加索引
理想的做法是仅仅在常常被搜索的列(以及表)上面创建索引。
CREATE INDEX PersonIndex
ON Person (LastName, FirstName)
删除
ALTER TABLE table_name DROP INDEX index_name
内建常用函数
http://www.jb51.net/article/40179.htm
以下是常用的数据类型:
- CHAR(length)固定长度字符串
- VARCHAR(length) 可变长度字符串
- TEXT 最大长度64KB的可变字符串
- DECIMAL(length,dec) 浮点数,前面是是位数,后面是小数位。
- DATE时期值,年月日
- TIME时间值,时分秒
- RNUM('value1','value2'.....)枚举法列表```
网友评论