1

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

我有一张放电视节目的桌子。我想在一个查询中搜索此表中的节目,并将结果与​​晚上节目前一天的所有节目进行排序。

我有一个输入名称 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 

有人可以帮助我吗?(我尝试使用带有两个请求的联盟 [一个用于白天,一个用于晚上],但我没有成功对结果进行排序,即使它们在两个请求中......)

4

1 回答 1

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 小时,你就可以按小时按顺序排列。)

于 2012-12-04T14:46:14.523 回答