我在phpmysql中尝试了这段代码
SELECT p.ID, p.post_title, p.post_name
FROM `wp6p_popularpostsdata` AS pps
INNER JOIN `wp6p_posts` AS p ON pps.`postid`= p.`ID`
WHERE p.post_type = "post"
AND pps.last_viewed > DATE_SUB(CURDATE(), INTERVAL 1 WEEK)
ORDER BY pps.`pageviews` DESC
LIMIT 4
它正确地给出了结果
1336Reading Between The Lines. reading-between-the-lines
824 Benefits of Watching Anime benefits-of-watching-anime
1427 The Day Goes By. life-goes-by
1950 Click here if you want to be rich want-to-be-rich
但是当我在我的php文件中使用它时,它会返回
在线之间阅读。在线之间阅读。这一天过去了。观看动画的好处
global $wpdb;
$interval = "1 WEEK";
$now = current_time('mysql');
$top4 = $wpdb->get_results(
'SELECT p.ID, p.post_title, p.post_name
FROM `' . $wpdb->prefix . 'popularpostssummary` AS pps
INNER JOIN `' . $wpdb->prefix . 'posts` AS p ON pps.`postid`= p.`ID`
WHERE p.post_type = "post"
AND pps.last_viewed > DATE_SUB("' . $now . '", INTERVAL ' . $interval . ')
ORDER BY pps.`pageviews` DESC
LIMIT 4;', ARRAY_A
);
foreach( $top4 AS $index => $row ) {
$class = ( $index == ( count( $top4 ) - 1 ) ) ? ' last' : '';
$url = get_permalink( $row['ID'] );
echo '<li class="trendingPost'.$class.'">' .
'<a href="' . $url . '">'.$row['post_title'].'</a></li>';
}
如何防止重复结果?
答案 0 :(得分:2)
使用exists
而不是join
:
SELECT p.ID, p.post_title, p.post_name
FROM wp6p_posts p
WHERE p.post_type = 'post' AND
EXISTS (SELECT 1
FROM wp6p_popularpostsdata pps
WHERE pps.postid = p.ID AND
pps.last_viewed > DATE_SUB(CURDATE(), INTERVAL 1 WEEK)
);
但是,这不允许您按pageviews
订购。相反,使用聚合:
SELECT p.ID, p.post_title, p.post_name
FROM wp6p_popularpostsdata pps INNER JOIN
wp6p_posts p
ON pps.postid = p.`ID`
WHERE p.post_type = 'post' AND
pps.last_viewed > DATE_SUB(CURDATE(), INTERVAL 1 WEEK)
GROUP BY p.ID, p.post_title, p.post_name
ORDER BY MAX(pps.pageviews) DESC
LIMIT 4;