简体   繁体   English

SQL查询按日期排序

[英]SQL query group by Date shuffle

I have a query like 我有一个查询

select id, item, date producer from table

The result is like this: 结果是这样的:

id         item            producer            date
1          apple            A                  2013-10-26
2          pear             A                  2013-10-26
3          peach            A                  2013-10-26
4          orange           B                  2013-10-26
5          strawberry       B                  2013-10-27
6          melon            B                  2013-10-27
7          apple2           A                  2013-10-27
8          orange3          A                  2013-10-27

I need to shuffle these data "order by DATE DESC" and get something like this: 我需要将这些数据“按DATE DESC顺序排序”,然后得到如下所示:

item            producer
orange3          A
melon            B
apple2           A
strawberry       B
pear             A
orange           B
apple            A
peach            A
melon            B

I DON'T want to display like this: 我不想这样显示:

ALL A ITEM... ALL B ITEM... Or shuffle something added today with something added yesterday... In my example I don't want to display "orange" before "orange3" 全部项目...全部项目...或将今天添加的内容与昨天添加的内容混洗...在我的示例中,我不想在“ orange3”之前显示“ orange”

My solution (but very slow) 我的解决方案(但很慢)

Select * from table where date = $date order by rand;
Select * from table where date = $date -1 order by rand;
select * from table where date = $date -2 order by rand;

(This is just a concept, $date cannot be decremented with this method) (这只是一个概念,不能使用此方法将$ date减1)

See if the following does the trick for you: 查看以下内容是否为您解决了问题:

SELECT * 
FROM `table` 
ORDER BY `date` DESC, RAND()

I just tried it and it seems to do what I think you want. 我只是尝试过,它似乎可以满足我的要求。

Edit 编辑

If you want to persist the "shuffle" then add a column of type DOUBLE named rnd , do 如果要保留“随机播放”,则添加一个名为rnd DOUBLE类型的列,请执行

UPDATE `table` SET rnd = RAND()

and then in your SELECT statement use 然后在您的SELECT语句中使用

.... ORDER BY `date` DESC, `rnd`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM