Maison >base de données >tutoriel mysql > 常用SQL语句汇总整理
1.SQL 插入语句得到自动生成的递增ID 值 insert into Table1(Name,des,num) values ('ltp','thisisbest',10); select @@identity as 'Id' 2.实现是1 或0 想显示为男或女 select name,Sex=(case Sexwhen '1' then '男'when '0' then '女'end)from Tablename
1.SQL 插入语句得到自动生成的递增ID 值
insert into Table1(Name,des,num) values ('ltp','thisisbest',10);
select @@identity as 'Id'
2.实现是1 或0 想显示为男或女
select name,Sex=(case Sex when '1' then '男' when '0' then '女' end) from Tablename
3.嵌套子查询
select a,b,c from Table1 where a IN (select a from Table2)
4.显示文章、提交人和最后回复时间
select a.title,a.username,b.adddate from tablename a,(select max(adddate) adddate from tablename where tablename.title=a.title) b
5.随机提取条记录的例子
SQL Server:Select Top 10 * From Tablename Order By NewID()
Access:Select Top 10 * From Tablename Order By Rnd(ID)
Rnd(ID) 其中的ID 是自动编号字段,可以利用其他任何数值来完成,比如用姓名字段UserName
Select Top 10 * From 表Order BY Rnd(Len(UserName))
MySql:Select * From 表Order By Rand() Limit 10
6.在同一表内找相同属性的记录
select UserID from Accounts_Users where UserName is not null group by UserID having count (*)>1
7.查询类别所有的产品对应数据
SELECT CategoryName,ProductName FROM Categories LEFT JOIN Products ON Categories.CategoryID = Products.CategoryID;
8.按范围查询编号在2 到5 之间的用户信息
select * from UserValue where UserID between 2 and 5;
9.日程安排提前5 分钟提醒
Select * from TabSchedule where datediff(minute,getdate(),开始时间)
10.得出某日期所在月份的最大天数
SELECT DAY(DATEADD(dd, -DAY('2008-02-13'),DATEADD(mm, 1, '2008-02-13'))) AS 'DayNumber'
11.按姓氏笔画排序
Select * From TableName Order By CustomerName Collate Chinese_PRC_Stroke_ci_as
12.通配符的一些用法
13.复制表结构(只复制结构,源表名:a,目标表名:b)
select * into b from a where 11 或 select top 0 * into [b] from [a]
14.复制表数据(复制数据,源表名:a,,目标表名:b)
insert into b(Name,des,num) select Name,des,num from Table1;
15. 创建分页存储过程
--创建分页的存储过程
create proc usp_GetPagedData
@pageIndex int, --页码
@pageSize int, --每页显示几条
@pageCount int output --共多少页
as
declare @count int
select @count = count(*) from TableName
set @pageCount = ceiling(@count*1.0/@pageSize)
select * from
(select *,ROW_NUMBER() over(order by ColumnName desc) as num
from TableName) as t
where num between (@pageIndex-1)*@pageSize + 1 and @pageIndex*@pageSize
--测试存储过程
declare @n int
exec usp_GetPagedData 3,4,@n output
print @n
转自: Server/48553.html