SQL常用知识与必须掌握的面试常问SQL语句

1.几个高级查询运算词

A: union 运算符[合并一起的数据]

UNION运算符通过组合其他两个结果表(例如 TABLE1 和 TABLE2)并消去表中任何重复行而派生出一个结果表。当 ALL 随UNION 一起使用时(即 UNIONALL),不消除重复行。两种情况下,派生表的每一行不是来自 TABLE1 就是来自 TABLE2。

B: except 运算符[1有但2没有的数据]

EXCEPT运算符通过包括所有在 TABLE1 中但不在 TABLE2 中的行并消除所有重复行而派生出一个结果表。当 ALL 随EXCEPT 一起使用时(EXCEPTALL),不消除重复行。

C:intersect 运算符[1,2都有的数据]

INTERSECT运算符通过只包括 TABLE1 和 TABLE2 中都有的行并消除所有重复行而派生出一个结果表。当 ALL 随INTERSECT 一起使用时(INTERSECTALL),不消除重复行。 注:使用运算词的几个查询结果行必须是一致的。

 

 

2.说明:使用外连接

A、left outer join: 左外连接(左连接):结果集几包括连接表的匹配行,也包括左连接表的所有行。

SQL:select a.a, a.b, a.c, b.c, b.d, b.f from a LEFT OUT JOIN b ON a.a =b.c

B:right outer join: 右外连接(右连接):结果集既包括连接表的匹配连接行,也包括右连接表的所有行。

C:full outer join: 全外连接:不仅包括符号连接表的匹配行,还包括两个连接表中的所有记录。

 

 

3.between的用法,between限制查询数据范围时包括了边界值,not between不包括

select* from table1 where time between time1 and time2

selecta,b,c, from table1 where a not between 数值1and 数值2

 

 

4.说明:in 的使用方法

select* from table1 where a [not] in (‘值1’,’值2’,’值4’,’值6’)

 

5.两张关联表,删除主表中已经在副表中没有的信息

deletefrom table1 where not exists ( select * from table2wheretable1.field1=table2.field1 )

 

6.四表连查问题:

select* from a left inner join b on a.a=b.b right inner join c on a.a=c.c inner joind on a/a=d.d where......

 

7.日程安排提前五分钟提醒:

Select* from 日程安排 wheredatediff(‘minute’,f 开始时间,getdate())>5

 

8.一条SQL语句搞定数据库分页

Selecttop 10 b.* from (select top 20 主键字段,排序字段 from 表名order by 排序字段 desc)a,表名 b where b.主键字段= a.主键字段 order by a.排序字段

 

9.前10条记录 

select top 10 * from table1 where 范围

 

10.选择在每一组B值相同的数据中对应的a最大的记录的所有信息,(用于论坛每月排行榜)

Selecta,b,c from tableta  wherea=(select max(a) from tabletb where tableb.b= tableta.b )

 

11.包括所有在ta中,但不在tb和tc中的行,并消除所有重复行而派生出的一个结果集.

(Selecta from ta)except(select a from tb)except(select a from tc)

 

12,随机抽取出10条数据

Select top 10 * from tablename order bynewid()

 

13.删除重复的记录

Delete from tablename where id notin(select max(id) from tablename group by col1,col2…..)

 

14.选择从10到15的记录

Select top 5 * from (select top 15* fromtable order by id asc) table_别名 order by id desc

posted @ 2013-05-09 14:05  `仅此而已  阅读(999)  评论(0编辑  收藏  举报