gpt4 book ai didi

mysql - wpdb 查询的限制结果

转载 作者:行者123 更新时间:2023-11-29 08:43:36 26 4
gpt4 key购买 nike

此代码仅显示当前类别中的标签,但是它获取所有标签(数百个),因此,我需要限制返回结果的数量并使它们随机。

如何让这个查询随机只得到 20 个结果?

/* Retrieve all tags from posts in selected categories */

$cats = array('beaches','mountains'); // Must be an array even if only one category
$cats_string = "'" . implode($cats,"','") . "'";
$sql = <<<EOSQL
SELECT DISTINCT t.*
FROM $wpdb->posts p
JOIN $wpdb->term_relationships tr ON p.ID = tr.object_id
JOIN $wpdb->term_taxonomy tt ON (tr.term_taxonomy_id = tt.term_taxonomy_id
AND tt.taxonomy = 'post_tag')
JOIN $wpdb->terms t ON tt.term_id = t.term_id
WHERE
p.ID IN (
SELECT p2.ID
FROM $wpdb->posts p2
JOIN $wpdb->term_relationships tr2 ON p2.ID = tr2.object_id
JOIN $wpdb->term_taxonomy tt2 ON (tr2.term_taxonomy_id = tt2.term_taxonomy_id AND tt2.taxonomy = 'category')
JOIN $wpdb->terms t2 ON (tt2.term_id = t2.term_id AND t2.name IN ($cats_string))
WHERE p2.post_type = 'post'
AND p2.post_status = 'publish'
AND p2.post_date <= NOW()
)
EOSQL;

$terms = $wpdb->get_results($sql);

// print_r($terms);

echo "<br />";
foreach ($terms as $term) {
echo "ID:$term->term_id NAME:$term->name SLUG:$term->slug<br />";
}

谢谢

最佳答案

您可以尝试 ORDER BY RAND() LIMIT 20,具体取决于您的表大小,这可以在适当的时间内运行。请参阅here有关何时避免 order by rand() 逻辑的一些详细信息。正如所建议的,在指定的帖子中,另一种方法是检索所有条目并随机选择 20 个条目,在 PHP 中而不是使用 mysql。

关于mysql - wpdb 查询的限制结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13108204/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com