I have a query where I’m trying to sort per row either by the latest postdate or the latest commentdate.
A post could have many comments so I need to get the max comment date for each row. If the postdate is greater than the commentdate cdate = postdate else if not cdate = max commentdate.
I am trying to achieve this using:
CASE WHEN max(wc.date_created) > wp.date_created THEN max(wc.date_created) ELSE wp.date_created END AS cdate
ORDER BY cdate DESC
Any help would be greatly appreciated.
Here is the full query (it seems to populate cdate with the commentdate for every row):
SELECT DISTINCT wp.p_id, wp.type, wp.value, wp.media, wp.youtube, wp.post_type, wp.tagedpersons, wp.title AS thetitle, wp.url, wp.description, wp.cur_image, wp.uip, wp.likes, wp.userid, wp.posted_by, wp.post AS postdata, wu . * , UNIX_TIMESTAMP( ) - wp.date_created AS TimeSpent, wp.date_created, wp.course,
CASE WHEN max(wc.date_created) > wp.date_created THEN max(wc.date_created) ELSE wp.date_created END AS cdate
FROM wallposts wp
INNER JOIN wallusers wu ON wu.mem_id = wp.userid
INNER JOIN wallcomments wc ON wc.post_id = wp.p_id
WHERE (
wp.userid IN (".$matches.") OR
(wp.userid IN (".$courses.") AND wp.course = 1) OR
wp.userid =".$user_id." OR
wp.tagedpersons LIKE '%".$user_id."%' OR
EXISTS (SELECT * FROM wallcomments
WHERE wp.p_id = wallcomments.post_id AND wallcomments.tagedpersons LIKE '%".$user_id."%')
)
GROUP BY wp.p_id
ORDER BY cdate DESC
Table structure – INNER JOIN wallcomments wc ON wc.post_id = wp.p_id
CREATE TABLE IF NOT EXISTS `wallposts` (
`p_id` int(11) NOT NULL AUTO_INCREMENT,
`post` text NOT NULL,
`type` varchar(55) NOT NULL,
`value` int(11) NOT NULL,
`date_created` int(11) NOT NULL,
`userid` varchar(255) NOT NULL,
`posted_by` int(11) NOT NULL,
`likes` int(11) NOT NULL,
`media` int(11) NOT NULL,
`uip` varchar(222) NOT NULL,
`title` varchar(255) NOT NULL,
`description` text NOT NULL,
`url` text NOT NULL,
`cur_image` text NOT NULL,
`post_type` tinyint(1) NOT NULL,
`youtube` text NOT NULL,
`tagedpersons` varchar(255) NOT NULL,
`course` int(255) NOT NULL DEFAULT '0',
`ctimespent` varchar(255) NOT NULL,
PRIMARY KEY (`p_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=537 ;
CREATE TABLE IF NOT EXISTS `wallcomments` (
`c_id` int(11) NOT NULL AUTO_INCREMENT,
`userid` int(11) NOT NULL,
`comments` text NOT NULL,
`date_created` int(11) NOT NULL,
`post_id` int(11) NOT NULL,
`clikes` int(11) NOT NULL,
`uip` varchar(222) NOT NULL,
`tagedpersons` varchar(255) NOT NULL,
`deleted` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`c_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=349 ;
Sample data:
wp.date_created and wc.date_created (format) – 1356008534
Sorted, works great…..
LEFT JOIN on the comments table was the key and also changed
TO
Here is the final query: