$wpdb->query() vs. $wpdb->get_results() vs. phpMyAdmin

I have this code:

$query = "SELECT * 
            FROM $wpdb->posts
                INNER JOIN $wpdb->postmeta 
                    ON $wpdb->posts.ID = $wpdb->postmeta.post_id
                INNER JOIN $wpdb->term_relationships 
                    ON $wpdb->posts.ID = $wpdb->term_relationships.object_id
            WHERE ((post_type="projects") OR (post_type="post_cost_codes"));";

$results = $wpdb->query($query); // Takes 1.5 seconds

I also tried this:

$query = "SELECT * 
            FROM $wpdb->posts
                INNER JOIN $wpdb->postmeta 
                    ON $wpdb->posts.ID = $wpdb->postmeta.post_id
                INNER JOIN $wpdb->term_relationships 
                    ON $wpdb->posts.ID = $wpdb->term_relationships.object_id
            WHERE ((post_type="projects") OR (post_type="post_cost_codes"));";

$results = $wpdb->get_results($query); // Still takes 1.5 seconds

But when I grab the query and put it in phpmyadmin:

(18588 total, Query took 0.0102 seconds.)
SELECT * FROM wp_dev_posts, wp_dev_postmeta, wp_dev_term_relationships WHERE ((post_type="projects") OR (post_type="post_cost_codes")) AND (wp_dev_posts.ID = wp_dev_postmeta.post_id) AND (wp_dev_posts.ID = wp_dev_term_relationships.object_id)
// Takes 0.0102 seconds

Why do both $wpdb methods take so much longer? The same query is copy and pasted directly on phpmyadmin, it takes the expected amount of time.

2 Answers
2

The difference is what is returned.

The WPDB query() method returns true for CREATE, ALTER, TRUNCATE and DROP queries, an integer of how many results for all other queries, or simply false if if there’s an error.

The WPDB get_results() method actually returns the entire result of the query (like you would get running the query in phpMyAdmin). You can return the result as an array or an object, depending on how you want to work with the results.

Leave a Comment