我有一个查询,我试图按最新的发布日期或最新的评论日期对每行进行排序。
一个帖子可能有很多评论,所以我需要获取每行的最大评论日期。如果 postdate 大于 commentdate cdate = postdate else if not cdate = max commentdate。
我正在尝试使用以下方法实现此目的:
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
任何帮助将不胜感激。
这是完整的查询(它似乎用每行的注释日期填充 cdate):
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
表结构 - 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 ;
样本数据:
wp.date_created 和 wc.date_created(格式) - 1356008534