简体   繁体   中英

MySQL GROUP BY query returns only one row

    $q2 =   "SELECT startdate, 
             GROUP_CONCAT(summary separator '<br />') as summary, 
             GROUP_CONCAT(TIME(startdate)) AS starttime, 
             GROUP_CONCAT(TIME(enddate)) AS endtime
             FROM oc_clndr_objects
             WHERE calendarid = $calID
             GROUP BY DATE(startdate)
             ORDER BY startdate ASC";

This above query is only returning one result (3 events for one 1 date as expected) - however there is 1 event that is repeating daily, and the query does not go beyond the first startdate.

I know it has something to do with the GROUP BY clause and something about Aggregation functions but I cannot wrap my head around it. - The output is visible at http://www.deliriousdreams.co.uk/ - "DJ Schedule Test"

Any help with correcting the slightly illegal SQL query would be much appreciated.

EDIT: Alright, groovy people, amended to DATE(startdate) AS startdate. One little niggle, after that I would like to be able to sort them by DATE and then TIME (earliest first) - Obviously both DATE and TIME are derived from the startdate (DATETIME stamp) - is this possible by amending the above query or would I have to do some PHP witchcraft?

You are selecting startdate but grouping by DATE(startdate)

If the field startdate is datetime and you want to group by date only then you should select a data and group by a date.

Try changing your query to this

         SELECT DATE(startdate) AS startdate, 
         GROUP_CONCAT(summary separator '<br />') as summary, 
         GROUP_CONCAT(TIME(startdate)) AS starttime, 
         GROUP_CONCAT(TIME(enddate)) AS endtime
         FROM oc_clndr_objects
         WHERE calendarid = $calID
         GROUP BY DATE(startdate)
         ORDER BY startdate ASC

I hope $calID is clean variable otherwise your code is subject to SQL injections

And it is done! This is the solution I was looking for...

SELECT
       DATE(startdate) AS startdate, 
       GROUP_CONCAT(summary separator '<br />') as summary, 
       GROUP_CONCAT(TIME(startdate)) AS starttime, 
       GROUP_CONCAT(TIME(enddate)) AS endtime
FROM
       (SELECT * FROM oc_clndr_objects ORDER BY startdate ASC) AS temp
WHERE calendarid = $calID
GROUP BY DATE(startdate)
ORDER BY DATE(startdate) ASC

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