如果置顶、会员时长、更新时间分别对应了表中的一个字段,那么是可以的
假定这几个字段是
top(是否置顶,1.置顶 0.不置顶)
vipDays 会员时长
updateTime (更新时间)
那么sql可以这么写
select * from table where type=1 order by top desc,vipDays desc,updateTime desc效果就是先top倒序(置顶的在前),top相同的就按会员时长倒序(时长越长越在前),若会员时长也相同就按更新时间倒序(最新的在前)
CREATE TABLE test
(
str VARCHAR(1),
time DATETIME
)
INSERT INTO ywtg.test (str, time) VALUES ('a', '2016-08-03 16:41:37')
INSERT INTO ywtg.test (str, time) VALUES ('b', '2016-08-10 23:42:26')
INSERT INTO ywtg.test (str, time) VALUES ('a', '2016-08-13 23:42:46')
INSERT INTO ywtg.test (str, time) VALUES ('b', '2016-08-14 23:42:58')
INSERT INTO ywtg.test (str, time) VALUES ('b', '2016-08-15 23:43:13')
如上是表结构和数据,**需求:组与组之间按时间从大到小排序,组内数据按从小到大排序.**
如上数据也就是b组在a组前,b组和a组 组内数据又按从小到大排序,实现sql如下:
SELECT tt.*
FROM test tt LEFT JOIN (
SELECT
@rownum := @rownum + 1 AS rownum,
test.str
FROM (SELECT @rownum := 0) r, (SELECT str
FROM test
GROUP BY str
ORDER BY time DESC) test
) aa ON tt.str = aa.str
ORDER BY aa.rownum, time
下面这个不知是否可行:
create table books(`id` int, `name` varchar(16),`type` varchar(16))insert into books(`id`,`name`,type)
select 1 as `id`, 'book11' as `name`, 'type1' as `type`
union all
select 2, 'book12', 'type1'
union all
select 3, 'book13', 'type1'
union all
select 4, 'book14', 'type1'
union all
select 5, 'book15', 'type1'
union all
select 6, 'book21', 'type2'
union all
select 7, 'book22', 'type2'
union all
select 8, 'book23', 'type2'
union all
select 9, 'book24', 'type2'
union all
select 10, 'book25', 'type2'
union all
select 11, 'book26', 'type2'
union all
select 12, 'book31', 'type3'
union all
select 13, 'book32', 'type3'
union all
select 14, 'book33', 'type3'
select t.`id`, t.`name`, t.type, t.rank
from (
select b.`id`, b.name, b.type,
if(@type = b.type, @rank := @rank + 1, @rank := 1) as rank,@type:=b.type
from (select id, name, type from books order by type asc, rand() desc) as b,
(select @type := null, @rank := 0) as a
) as t
where t.rank<=3
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)