SQL常用经典语句
--说明:几个高级查询运算词
A UNION 运算
UNION 运算符通过组合其他两个结果表(例如 TABLE1 TABLE2)并消去表中任何重复行而派生出一个结果表。当
ALL UNION 一起使用时(即 UNION ALL),不消除重复行。两种情况下,派生表的每一行不是来 TABLE1 就是
TABLE2
B EXCEPT 运算
EXCEPT 运算符通过包括所有在 TABLE1 中但不在 TABLE2 中的行并消除所有重复行而派生出一个结果表。当 ALL
EXCEPT 一起使用时 (EXCEPT ALL),不消除重复行
C INTERSECT 运算
INTERSECT 运算符通过只包 TABLE1 TABLE2 中都有的行并消除所有重复行而派生出一个结果表。当 ALL
INTERSECT 一起使用时 (INTERSECT ALL),不消除重复行
注:使用运算词的几个查询结果行必须是一致的
12、说明:使用外连
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
全外连接:不仅包括符号连接表的匹配行,还包括两个连接表中的所有记录
---------示例
----1、说明:in 的使用方
select * from table1 where a [not] in (‘1,’2,’4,’6)
----2.说明:列出数据库中所有用户表
select name from sysobjects where type = 'U'
----3.说明:随机取10条记
use Northwind
select top 10 * from orders order by newid()
go
---4.说明:选择1015的记
use Northwind
select top 5 * from (select top 15 * from orders order by orderid asc) temporders order by orderid desc
go
----5、说明:日程安排提前五分钟提
select * from 日程安排 where datediff('minute',f开始时,getdate())>5
----6、说明:删除重复记录
DELETE FROM TableName WHERE id not in (SELECT MAX(id) FROM TableName GROUP BY Col1,Col2,Col3,)
----7、说明:包括所有在 TableA 中但不在 TableB和TableC 中的行并消除所有重复行而派生出一个结果表
(select a from tableA ) except (select a from tableB) except (select a from tableC)
----8、说明:四表联查问题
select * from a left inner join b on a.a=b.b right inner join c on a.a=c.c inner join d on a.a=d.d
where ..
----9、说明:选择在每一组b值相同的数据中对应的a最大的记录的所有信(类似这样的用法可以用于论坛每月排行榜,
---- 每月热销产品分析,按科目成绩排,等等.)
select a,b,c from tablename ta where a=(select max(a) from tablename tb where tb.b=ta.b)
----10、说明:一条sql 语句搞定数据库分
select top 10 b.* from (select top 20 主键字段,排序字段 from 表名 order by 排序字段 desc) a,表名 b
where b.主键字段 = a.主键字段 order by a.排序字段文章转自:天高云淡📱 扫码关注公众号
扫描二维码关注我们,获取更多精彩内容
实时更新 · 干货满满