这是我的数据库表结构:
----------------------------------- | id | title | date | ----------------------------------- | 001 | my event OO1 | 04/02/2014 | | 002 | my event OO2 | 04/02/2014 | | 003 | my event OO3 | 04/02/2014 | | 004 | my event OO4 | 05/02/2014 | | 005 | my event OO5 | 05/02/2014 | | 006 | my event OO6 | 05/02/2014 | | 007 | my event OO7 | 05/02/2014 | | 008 | my event OO8 | 06/02/2014 | | 009 | my event OO9 | 06/02/2014 | -----------------------------------
我开始像它一样显示它:
04/02/2014 - my event OO1 - my event OO2 - my event OO3 05/02/2014 - my event OO4 - my event OO5 - my event OO6 - my event OO7 06/02/2014 - my event OO8 - my event OO9
但我希望每个日期随机显示1个结果(事件),如:
04/02/2014 - my event OO2 05/02/2014 - my event OO6 06/02/2014 - my event OO8
在我的sql结果中,我尝试了ORDER BY RAND() LIMIT 1
,但当然我没有按日期排序
所以结果是随机排序的
那么,如何对日期进行排序并获得随机结果?
答案 0 :(得分:3)
使用:
SELECT d1.date, (
SELECT d2.title
FROM table_1 d2
WHERE d2.date = d1.date
ORDER BY RAND()
LIMIT 1
) AS title
FROM table_1 d1
GROUP BY d1.date
HAVING COUNT(d1.date)>=1
ORDER BY d1.date ASC
您唯一需要更改的是表格的名称。请确保您只在table_1
个子句中将FROM
列为表格的实际名称。
您的想法是检索日期,然后执行子查询以在该日期内检索随机事件,方法是从同一个表中选择并加入日期。
答案 1 :(得分:2)
SELECT distinct t1.date,
(SELECT t2.ID, t2.title
FROM mytable as t2
WHERE t2.date = t1.date
ORDER BY RAND()
LIMIT 1) AS event_title
FROM mytable as t1
ORDER BY t1.date;
答案 2 :(得分:2)
一种方法
SELECT e.*
FROM
(
SELECT
(
SELECT id
FROM events
WHERE date = d.date
ORDER BY RAND()
LIMIT 1
) id
FROM
(
SELECT DISTINCT date
FROM events
) d
) q JOIN events e
ON q.id = e.id
ORDER BY date
示例输出:
| ID | TITLE | DATE | |----|--------------|------------------------------| | 2 | my event OO2 | April, 02 2014 00:00:00+0000 | | 4 | my event OO4 | May, 02 2014 00:00:00+0000 | | 8 | my event OO8 | June, 02 2014 00:00:00+0000 |
这是 SQLFiddle 演示