优化mysql查询以获得更好的性能

时间:2016-02-24 04:00:42

标签: mysql performance

我的SQL查询:

    SELECT 
        CONCAT(SUBSTR(p2.post_date,1,4), p2.post_title, p2.post_name) AS thumb, p.ID, p.post_name, p.post_title, p.post_content 
    FROM 
        wp_posts p 
        LEFT JOIN wp_postmeta m 
                 ON p.ID = m.post_id 
                 AND m.meta_value IS NOT NULL 
                 AND m.meta_key = '_thumbnail_id' 
        LEFT JOIN wp_posts p2 
                 ON m.meta_value = p2.ID 
        LEFT JOIN wp_term_relationships 
                 ON p.ID=wp_term_relationships.object_id 
        LEFT JOIN wp_term_taxonomy 
                 ON wp_term_taxonomy.term_taxonomy_id = wp_term_relationships.term_taxonomy_id 
        LEFT JOIN wp_terms 
                 ON wp_terms.term_id = wp_term_taxonomy.term_id 
    WHERE p.post_type = 'post' 
        AND p.post_status = 'publish' 
        AND wp_term_taxonomy.taxonomy = 'category' 
        AND wp_term_taxonomy.term_id = wp_terms.term_id 
        AND wp_terms.name = 'my_cat' 
    ORDER BY p.post_date DESC 
    LIMIT 0,50

性能不好,需要很长时间才能获得结果。请帮我优化以获得更好的性能。谢谢!

更新:

  • 我想从wordpress网站的类别中获取帖子。

  • 我从普通网站(不是wordpress)获取这些帖子,可以访问该wordpress网站的数据库

  • Wordpress网站有一些上述查询表:wp_posts,wp_postmeta,wp_term_relationships,wp_term_taxonomy,wp_terms(作为标准wordpress网站db)

  • 有没有更简单的方法从数据库获取wordpress帖子?

更新#2

谢谢大家。我创建了自己的解决方案。我可以使用内置的wpdb类从wordpress数据库中获取帖子。发布在这里任何人都需要它:

        include_once('path-to-wp-site/wp-load.php');
        global $wpdb;

        $query = "SELECT ID, post_date, post_title, post_name, post_content,
              CONCAT('http://your-wp-site.com/wp-content/uploads/',pm2.meta_value) AS post_image
        FROM $wpdb->posts p
        INNER JOIN $wpdb->term_relationships tr ON p.ID = tr.object_id
        INNER JOIN $wpdb->term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
              AND tt.taxonomy = 'category'
              AND tt.term_id IN (63)
        INNER JOIN $wpdb->postmeta pm ON p.ID = pm.post_id AND pm.meta_key = '_thumbnail_id'
        INNER JOIN $wpdb->postmeta pm2 ON pm.meta_value = pm2.post_id AND pm2.meta_key = '_wp_attached_file'
        WHERE p.post_status = 'publish'
              AND p.post_type = 'post'
              AND p.post_date BETWEEN SUBDATE(CURDATE(),INTERVAL 1 YEAR) AND ADDDATE(CURDATE(),INTERVAL 1 DAY)
        ORDER BY p.post_date DESC"

        $results = $wpdb->get_results($query, OBJECT);
        var_dump($results);

0 个答案:

没有答案