我怎么能改变这个查询

时间:2012-12-18 07:47:54

标签: mysql

My db records

SELECT * FROM (
      SELECT t1.eventId,t1.start_date,t1.end_date, COUNT(*) pos FROM events t1
        LEFT JOIN events t2 ON t1.start_date = t2.start_date AND t1.eventId <= t2.eventId
        WHERE t1.start_date BETWEEN  '2012-12-18' AND '2012-12-24'
      GROUP BY
        t1.eventId,t1.start_date
      ORDER BY 
        t1.start_date,pos ASC
      ) t
    WHERE
      pos <= 3;

enter image description here

为什么开始日期2012-12-21和2012-12-24不存在,

如果start_date不存在,那么我需要

的空值或空值

注意:我的数据库中没有21和24 ..的记录,但我的查询中需要一个空值

2 个答案:

答案 0 :(得分:0)

请使用以下查询并告诉我结果

SELECT * FROM (
      SELECT t1.eventId,t1.start_date,t1.end_date, COUNT(*) pos FROM events t1
        LEFT JOIN events t2 ON t1.start_date = t2.start_date AND t1.eventId <= t2.eventId
        WHERE t1.start_date >=  '2012-12-18' AND  t1.start_date <='2012-12-24'
      GROUP BY
        t1.eventId,t1.start_date
      ORDER BY 
        t1.start_date,pos ASC
      ) t
    WHERE
      pos <= 3;

答案 1 :(得分:0)

您可以使用HAVING消除外部查询:

SELECT t1.eventId,t1.start_date,t1.end_date, COUNT(*) pos FROM events t1
LEFT JOIN events t2 ON t1.start_date = t2.start_date AND t1.eventId <= t2.eventId
WHERE t1.start_date BETWEEN  '2012-12-18' AND '2012-12-24'
GROUP BY t1.eventId,t1.start_date
HAVING COUNT(*) <= 3
ORDER BY t1.start_date,pos ASC;

请注意插入此行:

HAVING COUNT(*) <= 3

这在逻辑上等同于您的外部查询正在执行的操作