网络编程
位置:首页>> 网络编程>> 数据库>> SQL语句实例说明 方便学习mysql的朋友(2)

SQL语句实例说明 方便学习mysql的朋友(2)

 来源:asp之家 发布时间:2012-11-30 20:02:43 

标签:SQL语句,mysql

索引的建立与删除:

索引的建立:

CREATE [UNIQUE]|[CLUSTER] INDEX <索引名> ON <表名>(<列名> [次序][,<列名> [次序]]……);

UNIQUE 表明此索引的每一个索引值只对应唯一的数据记录。

CLUSTER 表示要建立的索引是聚簇索引。

create unique index id_index on teacher(id asc);
对teacher表的id列建立unique索引,索引名为id_index

索引的删除:

DROP INDEX <索引名> ON <表名>

drop index id_index on teacher;
在teacher表中删除索引,索引名为id_index

另外的方法:

新建索引:

ALTER TABLE <表名> ADD [UNIQUE]|[CLUSTER] INDEX [<索引名>](<列名> [<次序>],[<列名> [<次序>]]……)

alter table teacher add unique index id_index(id asc);
在teacher表中对id列升序建立unique索引,索引的名字为id_index

删除索引:

ALTER TABLE <表名> DROP INDEX <索引名>

alter table teacher drop index id_index;
删除teacher表名为id_index的索引

数据库索引的建立有利也有弊,参考文章:

数据库索引的作用和优点缺点(一)

数据库索引的作用和优点缺点(二)

数据库建立索引的原则

数据查询:

SELECT [ALL|DISTINCT] <目标列表达式> [,<目标列表达式>]……

FROM <表名或视图名> [<表名或视图名>]……

[WHERE <条件表达式>]

[GROUP BY <列名1> [HAVING <条件表达式>]]

[ORDER BY <列名2> [ASC|DESC] [,<列名3> [ASC|DESC]]……];

查询经过计算的值:

select teacherId as id,salary - 100 as S from teacher;

查询经过计算的值,从teacher表中查询出teacherId字段,别名为id,并且查询出salary字段减去100后的字段,别名为S


使用函数和字符串:

select teacherid as id,'birth',salary - 20 as SA, lower(name) from teacher;

<目标表达式>可以是字符串常量和函数等,'birth' 为字符串常量,lower(name)为函数,将name字段以小写字母形式输出


消除取值重复的行:

select distinct name from teacher;

如果没有指定DISTINCT关键词,则缺省为ALL.


查询满足条件的元组:

WHERE子句常用的查询条件:

查询条件

谓词

比较

=, >, <, >=, <=, !=, <>, !>, !<

确定范围

BETWEEN AND, NOT BETWEEN AND

确定集合

IN, NOT IN

字符匹配

LIKE, NOT LIKE

空值

IS NULL, IS NOT NULL

多重条件(逻辑运算)

AND, OR, NOT



(1)比较大小:

select * from teacher where name = 'test';

select * from teacher where salary > 500;

select * from teacher where salary <> 500;

(2)确定范围:

select * from teacher where salary between 300 and 1000;

select * from teacher where salary not between 500 and 1000

(3)确定集合

select * from teacher where name in('test','test2');

select * from teacher where name not in('test','test2');

(4)字符匹配:

[NOT] LIKE '<匹配串>' [ESCAPE '<换码字符>']
<匹配串>可以是一个完整的字符串,也可以含有通配符%和_
%代表任意长度(长度可以是0)的字符。例如a%b表示以a开头,以b结尾的任意长度的字符串。如acb,addgb,ab

_代表任意单个字符。例如a_b表示以a开头,以b结尾的长度为3的任意字符串。如acb,afb等都满足该匹配串。

select * from teacher where name like '%2%‘;

select * from teacher where name like '_e%d';

注意一个汉字要占两个字符的位置。

(5)涉及空值查询:

select * from teacher where name is null;

select * from teacher where name is not null;

注意这里的"is"不能用符号(=)代替。

(6)多重条件查询:

select * from teacher where name = 'test' and salary between 400 and 800;

select * from teacher where name like '%s%' or salary = 500;


ORDER BY子句:

ORDER BY 子句对查询结果按照一个或多个属性列的升序(ASC)或降序(DESC)排列,缺省值为(ASC)

select salary from teacher order by salary asc;

select * from teacher order by name desc,salary asc;

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com