0

如何在此代码中插入“重复键”以删除重复的单词?还是您知道更好的方法?谢谢你!!

这是我的代码:

function sm_list_recent_searches($before = '', $after = '', $count = 20) {
// List the most recent successful searches.
    global $wpdb, $table_prefix;
    $count = intval($count);
    $results = $wpdb->get_results(
        "SELECT `terms`, `datetime`
        FROM `{$table_prefix}searchmeter_recent`
        WHERE 3 < `hits` AND CHAR_LENGTH(`terms`) > 4
        ORDER BY `datetime` DESC
        LIMIT $count");
    if (count($results)) {

        foreach ($results as $result) {
            echo '<a href="'. get_settings('home') . '/search/' . urlencode($result->terms) . '">'. htmlspecialchars($result->terms) .'</a>'.", ";
        }

    }
}
4

2 回答 2

3

ON DUPLICATE KEY UPDATE如果记录已经存在,则用于使插入更新记录。它不用于SELECT查询

您想要的是使用GROUP BY条款列上的子句将其折叠为唯一值。您可以使用MAX聚合函数来获取这些术语的最新记录的日期。

SELECT `terms`, MAX(`datetime`)
FROM `{$table_prefix}searchmeter_recent`
WHERE 3 < `hits` AND CHAR_LENGTH(`terms`) > 4
GROUP BY terms
ORDER BY `datetime` DESC
LIMIT $count

确保您在 terms 列上有一个索引,否则这将是一项非常昂贵的操作,尤其是当您使用它来进行自动完成时。您甚至可以考虑在插入时对术语进行分组以获得最佳性能。

于 2010-03-16T14:58:41.670 回答
1

您是否考虑过在查询中使用 distinct 关键字?这显示了它的作用:http: //newsourcemedia.com/blog/mysql-distinct-to-remove-duplicate-listing/

于 2010-03-16T14:47:11.280 回答