SQL语句收集

每个用户在 从表(t) 只获取一条 最新的 记录。适用于一对多,但每个主表记录只查询一条从表记录的情况。
addtime  -- 添加时间
userid -- 外键
select top 10 title from t where addtime in (select max(addtime) from t group by userid)
参考网址:
http://zhidao.baidu.com/link?url=-H1FS4dw5QTSpQQnaLTBvpIh1lgag4e6jabw2bIk7ZpTYM7n3PYl93Dhes4w3HVoOIbAvAIOcVu5RMIrBwmcwq


// 2014-08-20 update
// 获取某个分类下固定条数的记录,支持排序
// 文章表 art_art, 分类字段clsid

select * from
(
select id, title, clsid, num = row_number() over(partition by clsid order by addtime desc) from art_art
where clsid in (98, 102, 20)
) as tmp

where num <= 5

// 2015-02-09
SQL 全文索引相关 contains(), freetext() 语法
https://msdn.microsoft.com/en-us/library/ms187787.aspx

 
// 2015-05-20
SQL in 排序
select id, job_id, username, true_name as name, course, face_image as face, sort_id
from [TABLE_NAME]
where job_id in (1,10,11,12,13,14,2394) order by charindex(',' + rtrim(cast(job_id as varchar(10))) + ',', ',1,10,11,12,13,14,2394,'), sort_id asc;
数据按照in内部的ID排序 而不是默认的混乱的排序。
最后的 sort_id asc 会进行二次排序,结果如下:(job_id安装括号内顺序,sort_id按照 asc 升序)
图片

// 2016-04-03
// 在SQL Select 语句中使用 case when then 语句 自定义输出内容

select
title, username, danwei, classname, puttime,
(
case [source]
when 'shzh' then '装潢网'
when 'snzsxh' then '协会'
end
) as [source_name],
(
case [status]
when 10 then '处理中'
when 20 then '已处完成'
end
) as [status_name]
from [tablename]
where puttime > '2015-04-01' and recycle = 0
order by puttime desc

// 2016-05-10
// SQL 中的 intersect 用法
在一个多对多的关系表中, 假设有 产品表 PRD, 属性表ATTR, 关系表 RELS
RELS表中结构 PID | AID
现在需要读取AID 既包含 = 1 又包含 = 2 的产品ID, 单纯的IN 是一种或OR的关系, 这里需要且AND的关系, 所以先读取=1的然后再读取=2的, 再取交集即可
语句如下:
select id, name from PRD where id in ( select pid from rels where aid = 1 intersect select pid from rels where aid = 2 )
 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值