简体   繁体   中英

How could i alter this Query

我的数据库记录

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;

在此处输入图片说明

WHY start date 2012-12-21 and 2012-12-24 does not exist,

if start_date does not exist then, i need a null or empty value for

NOTE : no record for 21 and 24.. in my DB but i need a empty value in my query

Please use below query and tell me the result

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;

You can eliminate the outer query with a HAVING instead:

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;

Note the insertion of this line:

HAVING COUNT(*) <= 3

Which is logically equivalent to what your outer query is doing

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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