2012-10-28 77 views
0

此代碼僅顯示當前類別中的標籤,但它獲取所有標籤(數百個),因此我需要限制返回結果的數量並使其隨機。wpdb查詢的限制結果

如何使此查詢隨機獲得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 />"; 
} 

感謝

回答

2

您可以嘗試ORDER BY RAND() LIMIT 20,這取決於你的表尺寸,這能夠在體面的時間運行。有關何時避免order by rand()邏輯的一些細節見here。就像建議的那樣,在指定的文章中,另一種方法是檢索所有條目並隨機選擇20個條目,而不是使用mysql。

+0

感謝您的幫助,經過一些試驗和錯誤,我可以把參數放在正確的位置,現在它的作品:) –

+0

@Johnmido不客氣。 – dan