I
I
idccc2014-06-21 09:42:16
SQL
idccc, 2014-06-21 09:42:16

How to properly organize a query into several Wordpress database tables at once?

Good afternoon. A general question regarding the selection and processing of results from various Wordpress database tables (CMS does not really play a fundamental role). It matured from the desire to reproduce and optimize the standard queries of the engine in order to reduce the load on the database.
There is a query to the wp_posts table that stores Wordpress posts:

$posts = $wpdb->get_results("SELECT * FROM wp_posts {условия выборки});

Since the metadata for each post in Wordpress is stored in a separate wp_postmeta table (which is vital for displaying on the user's screen), additional queries are created for each post to the adjacent wp_postmeta table:
foreach ($posts as $post) : 
{...определяются некоторые переменные...}
$thumbmeta = $wpdb->get_var("SELECT meta_value FROM wp_postmeta WHERE post_id = '$thumbid' AND meta_key = '_wp_attachment_metadata'");
{...внутри цикла foreach на основе этих метаданных производятся парсинг и манипуляции с полученными значениями...}
<?php endforeach; ?>

The output of the combined results from the wp_posts and wp_postmeta tables is correct, but since a call is made to the external wp_postmeta table for each iteration of the loop, the total number of requests on the site increases in proportion to the number of displayed records. It is intuitively clear that in order to prevent this from happening, it is not necessary to do calls to the second table inside the loop.
The question is: how can you display related data from several tables in such a way that an increase in their number does not affect the increase in the number of queries in the database (as in the standard get_posts in Wordpress)?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Philip, 2014-06-21
@idccc

in a loop you make a request, and execute it 1 time after

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question