在一个查询中按日前一天和晚上排序日期

时间:2012-12-04 14:27:52

标签: mysql sorting

(首先:我是法国人,如果我犯了一些语法错误,我很抱歉......)

我有一张电视节目表。在一个查询中,我希望搜索此表中的程序,并使用当晚程序之前的所有程序对结果进行排序。

我有一个输入名称为fullDateStart,日期为DATETIME格式,用于提取HOUR()。

我在研究中使用LEFT JOIN。这是我的实际要求:

SELECT programId, programTitle, COUNT(*) AS score,
ROUND(startDate / 1000) AS start, ROUND(endDate / 1000) AS end
FROM people_appearances AS a
LEFT JOIN programsTable AS b ON a.programId = b.program_id
WHERE peopleId = :id AND timestamp > :twoWeeksAgo AND programId != 0
AND redif = 0 AND channel_id IN(1,2,3,5,6,7,8,9)
GROUP BY programId
ORDER BY score DESC, start DESC
LIMIT 0, 10

在这里尝试使用UNION:

SELECT * FROM (
    SELECT fullDateStart, programId, programTitle, COUNT(*) AS score1,
    ROUND(startDate / 1000) AS start, ROUND(endDate / 1000) AS end
    FROM people_appearances AS a
    LEFT JOIN db.epg_programs AS b ON a.programId = b.program_id
    WHERE HOUR(fullDateStart) > 6 AND HOUR(fullDateStart) <= 23
    AND peopleId = 826 AND timestamp > 1353420511000 AND programId != 0
    AND redif = 0 AND channel_id IN(1,2,3,5,6,7,8,9)
    GROUP BY programId

    UNION
    SELECT fullDateStart, programId, programTitle, COUNT(*) AS score2,
    ROUND(startDate / 1000) AS start, ROUND(endDate / 1000) AS end
    FROM people_appearances AS c
    LEFT JOIN db.epg_programs AS d ON c.programId =d.program_id
    WHERE HOUR(fullDateStart) >= 0 AND HOUR(fullDateStart) <= 6
    AND peopleId = 826 AND timestamp > 1353420511000 AND programId != 0
    AND redif = 0 AND channel_id IN(1,2,3,5,6,7,8,9)
    GROUP BY programId
    ) AS s3
ORDER BY score1 DESC,start DESC
LIMIT 0, 10 

有人可以帮我吗? (我尝试联盟有两个请求[一天一个,一个晚上]但我没有成功排序结果,即使他们有两个请求......)

1 个答案:

答案 0 :(得分:0)

您的查询中的问题是order by。您首先按分数排序,然后按开始日期排序。

如果目标是在一天内保留所有内容,那么请执行以下操作:

order by score desc, date(fulldatestart),
         (case when hour(fulldatestart) between 7 and 23 then 1
               else 2
          end),
         hour(fulldatestart)

我为order by添加了第三个条款,因此具有相同分数的程序按小时排序。

如果您希望与之前日相关联的凌晨,则需要执行以下操作:

order by score desc, date(fulldatestart - interval 7 hour),
         hour(fulldatestart - interval 7 hour)

(一旦你减去7个小时,你可以按小时保持秩序。)