<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>[29940] trunk: Overhaul SQL generating logic in WP_Meta_Query to avoid unnecessary table joins.</title>
</head>
<body>

<style type="text/css"><!--
#msg dl.meta { border: 1px #006 solid; background: #369; padding: 6px; color: #fff; }
#msg dl.meta dt { float: left; width: 6em; font-weight: bold; }
#msg dt:after { content:':';}
#msg dl, #msg dt, #msg ul, #msg li, #header, #footer, #logmsg { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt;  }
#msg dl a { font-weight: bold}
#msg dl a:link    { color:#fc3; }
#msg dl a:active  { color:#ff0; }
#msg dl a:visited { color:#cc6; }
h3 { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt; font-weight: bold; }
#msg pre { overflow: auto; background: #ffc; border: 1px #fa0 solid; padding: 6px; }
#logmsg { background: #ffc; border: 1px #fa0 solid; padding: 1em 1em 0 1em; }
#logmsg p, #logmsg pre, #logmsg blockquote { margin: 0 0 1em 0; }
#logmsg p, #logmsg li, #logmsg dt, #logmsg dd { line-height: 14pt; }
#logmsg h1, #logmsg h2, #logmsg h3, #logmsg h4, #logmsg h5, #logmsg h6 { margin: .5em 0; }
#logmsg h1:first-child, #logmsg h2:first-child, #logmsg h3:first-child, #logmsg h4:first-child, #logmsg h5:first-child, #logmsg h6:first-child { margin-top: 0; }
#logmsg ul, #logmsg ol { padding: 0; list-style-position: inside; margin: 0 0 0 1em; }
#logmsg ul { text-indent: -1em; padding-left: 1em; }#logmsg ol { text-indent: -1.5em; padding-left: 1.5em; }
#logmsg > ul, #logmsg > ol { margin: 0 0 1em 0; }
#logmsg pre { background: #eee; padding: 1em; }
#logmsg blockquote { border: 1px solid #fa0; border-left-width: 10px; padding: 1em 1em 0 1em; background: white;}
#logmsg dl { margin: 0; }
#logmsg dt { font-weight: bold; }
#logmsg dd { margin: 0; padding: 0 0 0.5em 0; }
#logmsg dd:before { content:'\00bb';}
#logmsg table { border-spacing: 0px; border-collapse: collapse; border-top: 4px solid #fa0; border-bottom: 1px solid #fa0; background: #fff; }
#logmsg table th { text-align: left; font-weight: normal; padding: 0.2em 0.5em; border-top: 1px dotted #fa0; }
#logmsg table td { text-align: right; border-top: 1px dotted #fa0; padding: 0.2em 0.5em; }
#logmsg table thead th { text-align: center; border-bottom: 1px solid #fa0; }
#logmsg table th.Corner { text-align: left; }
#logmsg hr { border: none 0; border-top: 2px dashed #fa0; height: 1px; }
#header, #footer { color: #fff; background: #636; border: 1px #300 solid; padding: 6px; }
#patch { width: 100%; }
#patch h4 {font-family: verdana,arial,helvetica,sans-serif;font-size:10pt;padding:8px;background:#369;color:#fff;margin:0;}
#patch .propset h4, #patch .binary h4 {margin:0;}
#patch pre {padding:0;line-height:1.2em;margin:0;}
#patch .diff {width:100%;background:#eee;padding: 0 0 10px 0;overflow:auto;}
#patch .propset .diff, #patch .binary .diff  {padding:10px 0;}
#patch span {display:block;padding:0 10px;}
#patch .modfile, #patch .addfile, #patch .delfile, #patch .propset, #patch .binary, #patch .copfile {border:1px solid #ccc;margin:10px 0;}
#patch ins {background:#dfd;text-decoration:none;display:block;padding:0 10px;}
#patch del {background:#fdd;text-decoration:none;display:block;padding:0 10px;}
#patch .lines, .info {color:#888;background:#fff;}
--></style>
<div id="msg">
<dl class="meta" style="font-size: 105%">
<dt style="float: left; width: 6em; font-weight: bold">Revision</dt> <dd><a style="font-weight: bold" href="https://core.trac.wordpress.org/changeset/29940">29940</a><script type="application/ld+json">{"@context":"http://schema.org","@type":"EmailMessage","description":"Review this Commit","action":{"@type":"ViewAction","url":"https://core.trac.wordpress.org/changeset/29940","name":"Review Commit"}}</script></dd>
<dt style="float: left; width: 6em; font-weight: bold">Author</dt> <dd>boonebgorges</dd>
<dt style="float: left; width: 6em; font-weight: bold">Date</dt> <dd>2014-10-17 20:20:04 +0000 (Fri, 17 Oct 2014)</dd>
</dl>

<pre style='padding-left: 1em; margin: 2em 0; border-left: 2px solid #ccc; line-height: 1.25; font-size: 105%; font-family: sans-serif'>Overhaul SQL generating logic in WP_Meta_Query to avoid unnecessary table joins.

The logic used to generate clause SQL in `WP_Meta_Query` is somewhat arcane,
stemming mostly from an ongoing effort to eliminate costly table joins when
they are not necessary. By systematizing the process of looking for shareable
joins - as was done in `WP_Tax_Query` <a href="https://core.trac.wordpress.org/changeset/29902">[29902]</a> - it becomes possible to simplify
the construction of SQL queries in `get_sql_for_clause()`. Moreover, the
simplified logic is actually considerably better at identifying shareable
joins, such that certain uses of `WP_Meta_Query` will see joins reduced by 50%
or more.

Includes integration tests for a representative cross-section of the query
clause combinations that result in shared table aliases.

Props boonebgorges, sc0ttkclark.
See <a href="https://core.trac.wordpress.org/ticket/24093">#24093</a>.</pre>

<h3>Modified Paths</h3>
<ul>
<li><a href="#trunksrcwpincludesmetaphp">trunk/src/wp-includes/meta.php</a></li>
<li><a href="#trunktestsphpunittestsmetaqueryphp">trunk/tests/phpunit/tests/meta/query.php</a></li>
<li><a href="#trunktestsphpunittestspostqueryphp">trunk/tests/phpunit/tests/post/query.php</a></li>
</ul>

</div>
<div id="patch">
<h3>Diff</h3>
<a id="trunksrcwpincludesmetaphp"></a>
<div class="modfile"><h4 style="background-color: #eee; color: inherit; margin: 1em 0; padding: 1.3em; font-size: 115%">Modified: trunk/src/wp-includes/meta.php</h4>
<pre class="diff"><span>
<span class="info" style="display: block; padding: 0 10px; color: #888">--- trunk/src/wp-includes/meta.php    2014-10-17 19:16:26 UTC (rev 29939)
+++ trunk/src/wp-includes/meta.php      2014-10-17 20:20:04 UTC (rev 29940)
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -987,6 +987,10 @@
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><span class="cx" style="display: block; padding: 0 10px">                        // First-order clause.
</span><span class="cx" style="display: block; padding: 0 10px">                        } else if ( $this->is_first_order_clause( $query ) ) {
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+                                if ( isset( $query['value'] ) && array() === $query['value'] ) {
+                                       unset( $query['value'] );
+                               }
+
</ins><span class="cx" style="display: block; padding: 0 10px">                                 $clean_queries[] = $query;
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><span class="cx" style="display: block; padding: 0 10px">                        // Otherwise, it's a nested query, so we recurse.
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -1167,7 +1171,12 @@
</span><span class="cx" style="display: block; padding: 0 10px">         * }
</span><span class="cx" style="display: block; padding: 0 10px">         */
</span><span class="cx" style="display: block; padding: 0 10px">        protected function get_sql_clauses() {
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-                $sql = $this->get_sql_for_query( $this->queries );
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+         /*
+                * $queries are passed by reference to get_sql_for_query() for recursion.
+                * To keep $this->queries unaltered, pass a copy.
+                */
+               $queries = $this->queries;
+               $sql = $this->get_sql_for_query( $queries );
</ins><span class="cx" style="display: block; padding: 0 10px"> 
</span><span class="cx" style="display: block; padding: 0 10px">                if ( ! empty( $sql['where'] ) ) {
</span><span class="cx" style="display: block; padding: 0 10px">                        $sql['where'] = ' AND ' . $sql['where'];
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -1195,7 +1204,7 @@
</span><span class="cx" style="display: block; padding: 0 10px">         *     @type string $where SQL fragment to append to the main WHERE clause.
</span><span class="cx" style="display: block; padding: 0 10px">         * }
</span><span class="cx" style="display: block; padding: 0 10px">         */
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-        protected function get_sql_for_query( $query, $depth = 0 ) {
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+ protected function get_sql_for_query( &$query, $depth = 0 ) {
</ins><span class="cx" style="display: block; padding: 0 10px">                 $sql_chunks = array(
</span><span class="cx" style="display: block; padding: 0 10px">                        'join'  => array(),
</span><span class="cx" style="display: block; padding: 0 10px">                        'where' => array(),
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -1211,7 +1220,7 @@
</span><span class="cx" style="display: block; padding: 0 10px">                        $indent .= "  ";
</span><span class="cx" style="display: block; padding: 0 10px">                }
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-                foreach ( $query as $key => $clause ) {
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+         foreach ( $query as $key => &$clause ) {
</ins><span class="cx" style="display: block; padding: 0 10px">                         if ( 'relation' === $key ) {
</span><span class="cx" style="display: block; padding: 0 10px">                                $relation = $query['relation'];
</span><span class="cx" style="display: block; padding: 0 10px">                        } else if ( is_array( $clause ) ) {
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -1278,7 +1287,7 @@
</span><span class="cx" style="display: block; padding: 0 10px">         *     @type string $where SQL fragment to append to the main WHERE clause.
</span><span class="cx" style="display: block; padding: 0 10px">         * }
</span><span class="cx" style="display: block; padding: 0 10px">         */
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-        public function get_sql_for_clause( $clause, $parent_query ) {
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+ public function get_sql_for_clause( &$clause, $parent_query ) {
</ins><span class="cx" style="display: block; padding: 0 10px">                 global $wpdb;
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><span class="cx" style="display: block; padding: 0 10px">                $sql_chunks = array(
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -1286,16 +1295,13 @@
</span><span class="cx" style="display: block; padding: 0 10px">                        'join' => array(),
</span><span class="cx" style="display: block; padding: 0 10px">                );
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-                $i = count( $this->table_aliases );
-               $alias = $i ? 'mt' . $i : $this->meta_table;
-
</del><span class="cx" style="display: block; padding: 0 10px">                 if ( isset( $clause['compare'] ) ) {
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-                        $meta_compare = strtoupper( $clause['compare'] );
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+                 $clause['compare'] = strtoupper( $clause['compare'] );
</ins><span class="cx" style="display: block; padding: 0 10px">                 } else {
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-                        $meta_compare = isset( $clause['value'] ) && is_array( $clause['value'] ) ? 'IN' : '=';
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+                 $clause['compare'] = isset( $clause['value'] ) && is_array( $clause['value'] ) ? 'IN' : '=';
</ins><span class="cx" style="display: block; padding: 0 10px">                 }
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-                if ( ! in_array( $meta_compare, array(
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+         if ( ! in_array( $clause['compare'], array(
</ins><span class="cx" style="display: block; padding: 0 10px">                         '=', '!=', '>', '>=', '<', '<=',
</span><span class="cx" style="display: block; padding: 0 10px">                        'LIKE', 'NOT LIKE',
</span><span class="cx" style="display: block; padding: 0 10px">                        'IN', 'NOT IN',
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -1303,59 +1309,63 @@
</span><span class="cx" style="display: block; padding: 0 10px">                        'EXISTS', 'NOT EXISTS',
</span><span class="cx" style="display: block; padding: 0 10px">                        'REGEXP', 'NOT REGEXP', 'RLIKE'
</span><span class="cx" style="display: block; padding: 0 10px">                ) ) ) {
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-                        $meta_compare = '=';
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+                 $clause['compare'] = '=';
</ins><span class="cx" style="display: block; padding: 0 10px">                 }
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-                /*
-                * There are a number of different query structures that get
-                * built in different ways.
-                * 1. Key-only clauses - (a) clauses without a 'value' key that
-                *    appear in the context of an OR relation and do not use
-                *    'NOT EXISTS' as the 'compare', or (b) clauses with an
-                *    empty array for 'value'.
-                */
-               if ( ! empty( $clause['key'] ) && (
-                       ( ! array_key_exists( 'value', $clause ) && 'NOT EXISTS' !== $meta_compare && 'OR' === $parent_query['relation'] ) ||
-                       ( isset( $clause['value'] ) && is_array( $clause['value'] ) && empty( $clause['value'] ) )
-               ) ) {
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+         $meta_compare = $clause['compare'];
</ins><span class="cx" style="display: block; padding: 0 10px"> 
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-                        $alias = $this->meta_table;
-                       $sql_chunks['join'][] = " INNER JOIN $this->meta_table ON ($this->primary_table.$this->primary_id_column = $alias.$this->meta_id_column)";
-                       $sql_chunks['where'][] = $wpdb->prepare( "$this->meta_table.meta_key = %s", trim( $clause['key'] ) );
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+         // First build the JOIN clause, if one is required.
+               $join = '';
</ins><span class="cx" style="display: block; padding: 0 10px"> 
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-                // 2. NOT EXISTS.
-               } else if ( 'NOT EXISTS' === $meta_compare ) {
-                       $join  = " LEFT JOIN $this->meta_table";
-                       $join .= $i ? " AS $alias" : '';
-                       $join .= $wpdb->prepare( " ON ($this->primary_table.$this->primary_id_column = $alias.$this->meta_id_column AND $alias.meta_key = %s )", $clause['key'] );
-                       $sql_chunks['join'][] = $join;
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+         // We prefer to avoid joins if possible. Look for an existing join compatible with this clause.
+               $alias = $this->find_compatible_table_alias( $clause, $parent_query );
+               if ( false === $alias ) {
+                       $i = count( $this->table_aliases );
+                       $alias = $i ? 'mt' . $i : $this->meta_table;
</ins><span class="cx" style="display: block; padding: 0 10px"> 
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-                        $sql_chunks['where'][] = $alias . '.' . $this->meta_id_column . ' IS NULL';
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+                 // JOIN clauses for NOT EXISTS have their own syntax.
+                       if ( 'NOT EXISTS' === $meta_compare ) {
+                               $join .= " LEFT JOIN $this->meta_table";
+                               $join .= $i ? " AS $alias" : '';
+                               $join .= $wpdb->prepare( " ON ($this->primary_table.$this->primary_id_column = $alias.$this->meta_id_column AND $alias.meta_key = %s )", $clause['key'] );
+                               $sql_chunks['join'][] = $join;
</ins><span class="cx" style="display: block; padding: 0 10px"> 
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-                // 3. EXISTS and other key-only queries.
-               } else if ( 'EXISTS' === $meta_compare || ( ! empty( $clause['key'] ) && ! array_key_exists( 'value', $clause ) ) ) {
-                       $join  = " INNER JOIN $this->meta_table";
-                       $join .= $i ? " AS $alias" : '';
-                       $join .= " ON ( $this->primary_table.$this->primary_id_column = $alias.$this->meta_id_column )";
-                       $sql_chunks['join'][] = $join;
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+                 // All other JOIN clauses.
+                       } else {
+                               $alias = $this->find_compatible_table_alias( $clause, $parent_query );
+                               if ( false === $alias ) {
+                                       $alias = $i ? 'mt' . $i : $this->meta_table;
</ins><span class="cx" style="display: block; padding: 0 10px"> 
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-                        $sql_chunks['where'][] = $wpdb->prepare( $alias . '.meta_key = %s', trim( $clause['key'] ) );
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+                                 $join .= " INNER JOIN $this->meta_table";
+                                       $join .= $i ? " AS $alias" : '';
+                                       $join .= " ON ( $this->primary_table.$this->primary_id_column = $alias.$this->meta_id_column )";
+                               }
+                       }
</ins><span class="cx" style="display: block; padding: 0 10px"> 
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-                // 4. Clauses that have a value.
-               } else if ( array_key_exists( 'value', $clause ) ) {
-                       $join  = " INNER JOIN $this->meta_table";
-                       $join .= $i ? " AS $alias" : '';
-                       $join .= " ON ($this->primary_table.$this->primary_id_column = $alias.$this->meta_id_column)";
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+                 $this->table_aliases[] = $alias;
</ins><span class="cx" style="display: block; padding: 0 10px">                         $sql_chunks['join'][] = $join;
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+                }
</ins><span class="cx" style="display: block; padding: 0 10px"> 
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-                        if ( ! empty( $clause['key'] ) ) {
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+         // Save the alias to this clause, for future siblings to find.
+               $clause['alias'] = $alias;
+
+               // Next, build the WHERE clause.
+               $where = '';
+
+               // meta_key.
+               if ( array_key_exists( 'key', $clause ) ) {
+                       if ( 'NOT EXISTS' === $meta_compare ) {
+                               $sql_chunks['where'][] = $alias . '.' . $this->meta_id_column . ' IS NULL';
+                       } else {
</ins><span class="cx" style="display: block; padding: 0 10px">                                 $sql_chunks['where'][] = $wpdb->prepare( "$alias.meta_key = %s", trim( $clause['key'] ) );
</span><span class="cx" style="display: block; padding: 0 10px">                        }
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+                }
</ins><span class="cx" style="display: block; padding: 0 10px"> 
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+                // meta_value.
+               if ( array_key_exists( 'value', $clause ) ) {
+                       $meta_value = $clause['value'];
</ins><span class="cx" style="display: block; padding: 0 10px">                         $meta_type = $this->get_cast_for_type( isset( $clause['type'] ) ? $clause['type'] : '' );
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-                        $meta_value = isset( $clause['value'] ) ? $clause['value'] : '';
-
</del><span class="cx" style="display: block; padding: 0 10px">                         if ( in_array( $meta_compare, array( 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN' ) ) ) {
</span><span class="cx" style="display: block; padding: 0 10px">                                if ( ! is_array( $meta_value ) ) {
</span><span class="cx" style="display: block; padding: 0 10px">                                        $meta_value = preg_split( '/[,\s]+/', $meta_value );
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -1364,19 +1374,34 @@
</span><span class="cx" style="display: block; padding: 0 10px">                                $meta_value = trim( $meta_value );
</span><span class="cx" style="display: block; padding: 0 10px">                        }
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-                        if ( 'IN' == substr( $meta_compare, -2 ) ) {
-                               $meta_compare_string = '(' . substr( str_repeat( ',%s', count( $meta_value ) ), 1 ) . ')';
-                       } elseif ( 'BETWEEN' == substr( $meta_compare, -7 ) ) {
-                               $meta_value = array_slice( $meta_value, 0, 2 );
-                               $meta_compare_string = '%s AND %s';
-                       } elseif ( 'LIKE' == $meta_compare || 'NOT LIKE' == $meta_compare ) {
-                               $meta_value = '%' . $wpdb->esc_like( $meta_value ) . '%';
-                               $meta_compare_string = '%s';
-                       } else {
-                               $meta_compare_string = '%s';
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+                 switch ( $meta_compare ) {
+                               case 'IN' :
+                               case 'NOT IN' :
+                                       $meta_compare_string = '(' . substr( str_repeat( ',%s', count( $meta_value ) ), 1 ) . ')';
+                                       $where = $wpdb->prepare( $meta_compare_string, $meta_value );
+                                       break;
+
+                               case 'BETWEEN' :
+                               case 'NOT BETWEEN' :
+                                       $meta_value = array_slice( $meta_value, 0, 2 );
+                                       $where = $wpdb->prepare( '%s AND %s', $meta_value );
+                                       break;
+
+                               case 'LIKE' :
+                               case 'NOT LIKE' :
+                                       $meta_value = '%' . $wpdb->esc_like( $meta_value ) . '%';
+                                       $where = $wpdb->prepare( '%s', $meta_value );
+                                       break;
+
+                               default :
+                                       $where = $wpdb->prepare( '%s', $meta_value );
+                                       break;
+
</ins><span class="cx" style="display: block; padding: 0 10px">                         }
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-                        $sql_chunks['where'][] = $wpdb->prepare( "CAST($alias.meta_value AS {$meta_type}) {$meta_compare} {$meta_compare_string}", $meta_value );
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+                 if ( $where ) {
+                               $sql_chunks['where'][] = "CAST($alias.meta_value AS {$meta_type}) {$meta_compare} {$where}";
+                       }
</ins><span class="cx" style="display: block; padding: 0 10px">                 }
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><span class="cx" style="display: block; padding: 0 10px">                /*
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -1387,10 +1412,62 @@
</span><span class="cx" style="display: block; padding: 0 10px">                        $sql_chunks['where'] = array( '( ' . implode( ' AND ', $sql_chunks['where'] ) . ' )' );
</span><span class="cx" style="display: block; padding: 0 10px">                }
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-                $this->table_aliases[] = $alias;
-
</del><span class="cx" style="display: block; padding: 0 10px">                 return $sql_chunks;
</span><span class="cx" style="display: block; padding: 0 10px">        }
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+
+       /**
+        * Identify an existing table alias that is compatible with the current query clause.
+        *
+        * We avoid unnecessary table joins by allowing each clause to look for
+        * an existing table alias that is compatible with the query that it
+        * needs to perform. An existing alias is compatible if (a) it is a
+        * sibling of $clause (ie, it's under the scope of the same relation),
+        * and (b) the combination of operator and relation between the clauses
+        * allows for a shared table join. In the case of WP_Meta_Query, this
+        * only applies to IN clauses that are connected by the relation OR.
+        *
+        * @since 4.1.0
+        * @access protected
+        *
+        * @param  array       $clause       Query clause.
+        * @param  array       $parent_query Parent query of $clause.
+        * @return string|bool Table alias if found, otherwise false.
+        */
+       protected function find_compatible_table_alias( $clause, $parent_query ) {
+               $alias = false;
+
+               foreach ( $parent_query as $sibling ) {
+                       // If the sibling has no alias yet, there's nothing to check.
+                       if ( empty( $sibling['alias'] ) ) {
+                               continue;
+                       }
+
+                       // We're only interested in siblings that are first-order clauses.
+                       if ( ! is_array( $sibling ) || ! $this->is_first_order_clause( $sibling ) ) {
+                               continue;
+                       }
+
+                       $compatible_compares = array();
+
+                       // Clauses connected by OR can share joins as long as they have "positive" operators.
+                       if ( 'OR' === $parent_query['relation'] ) {
+                               $compatible_compares = array( '=', 'IN', 'BETWEEN', 'LIKE', 'REGEXP', 'RLIKE', '>', '>=', '<', '<=' );
+
+                       // Clauses joined by AND with "negative" operators share a join only if they also share a key.
+                       } else if ( isset( $sibling['key'] ) && isset( $clause['key'] ) && $sibling['key'] === $clause['key'] ) {
+                               $compatible_compares = array( '!=', 'NOT IN', 'NOT LIKE' );
+                       }
+
+                       $clause_compare  = strtoupper( $clause['compare'] );
+                       $sibling_compare = strtoupper( $sibling['compare'] );
+                       if ( in_array( $clause_compare, $compatible_compares ) && in_array( $sibling_compare, $compatible_compares ) ) {
+                               $alias = $sibling['alias'];
+                               break;
+                       }
+               }
+
+               return apply_filters( 'meta_query_find_compatible_table_alias', $alias, $clause, $parent_query, $this ) ;
+       }
</ins><span class="cx" style="display: block; padding: 0 10px"> }
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><span class="cx" style="display: block; padding: 0 10px"> /**
</span></span></pre></div>
<a id="trunktestsphpunittestsmetaqueryphp"></a>
<div class="modfile"><h4 style="background-color: #eee; color: inherit; margin: 1em 0; padding: 1.3em; font-size: 115%">Modified: trunk/tests/phpunit/tests/meta/query.php</h4>
<pre class="diff"><span>
<span class="info" style="display: block; padding: 0 10px; color: #888">--- trunk/tests/phpunit/tests/meta/query.php  2014-10-17 19:16:26 UTC (rev 29939)
+++ trunk/tests/phpunit/tests/meta/query.php    2014-10-17 20:20:04 UTC (rev 29940)
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -73,7 +73,7 @@
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><span class="cx" style="display: block; padding: 0 10px">                $sql = $query->get_sql( 'post', $wpdb->posts, 'ID' );
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-                $this->assertEquals( 2, substr_count( $sql['join'], 'INNER JOIN' ) );
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+         $this->assertEquals( 1, substr_count( $sql['join'], 'INNER JOIN' ) );
</ins><span class="cx" style="display: block; padding: 0 10px">         }
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><span class="cx" style="display: block; padding: 0 10px">        /**
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -476,12 +476,7 @@
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><span class="cx" style="display: block; padding: 0 10px">                $sql = $query->get_sql( 'post', $wpdb->posts, 'ID', $this );
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-                // We should have 2 joins - one for my_first_key and one for my_second_key
-               $this->assertEquals( 2, substr_count( $sql['join'], 'JOIN' ) );
-
-               // The WHERE should check my_third_key against an unaliased table
-               $this->assertEquals( 1, substr_count( $sql['where'], "$wpdb->postmeta.meta_key = 'my_third_key'" ) );
-
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+         $this->assertEquals( 3, substr_count( $sql['join'], 'JOIN' ) );
</ins><span class="cx" style="display: block; padding: 0 10px">         }
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><span class="cx" style="display: block; padding: 0 10px">        /**
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -546,9 +541,6 @@
</span><span class="cx" style="display: block; padding: 0 10px">                // NOT EXISTS compare queries are not key-only so should not be non-aliased
</span><span class="cx" style="display: block; padding: 0 10px">                $this->assertSame( 0, substr_count( $sql['where'], "$wpdb->postmeta.meta_key = 'baz'" ) );
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-                // When a value exists, it's not a key-only query
-               $this->assertSame( 0, substr_count( $sql['where'], "$wpdb->postmeta.meta_key = 'barry'" ) );
-
</del><span class="cx" style="display: block; padding: 0 10px">                 // 'AND' queries don't have key-only queries
</span><span class="cx" style="display: block; padding: 0 10px">                $query2 = new WP_Meta_Query( array(
</span><span class="cx" style="display: block; padding: 0 10px">                        'relation' => 'AND',
</span></span></pre></div>
<a id="trunktestsphpunittestspostqueryphp"></a>
<div class="modfile"><h4 style="background-color: #eee; color: inherit; margin: 1em 0; padding: 1.3em; font-size: 115%">Modified: trunk/tests/phpunit/tests/post/query.php</h4>
<pre class="diff"><span>
<span class="info" style="display: block; padding: 0 10px; color: #888">--- trunk/tests/phpunit/tests/post/query.php  2014-10-17 19:16:26 UTC (rev 29939)
+++ trunk/tests/phpunit/tests/post/query.php    2014-10-17 20:20:04 UTC (rev 29940)
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -647,6 +647,385 @@
</span><span class="cx" style="display: block; padding: 0 10px">        }
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><span class="cx" style="display: block; padding: 0 10px">        /**
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+         * @ticket 24093
+        */
+       public function test_meta_query_relation_or_compare_equals() {
+               $posts = $this->factory->post->create_many( 4 );
+               add_post_meta( $posts[0], 'color', 'orange' );
+               add_post_meta( $posts[1], 'color', 'blue' );
+               add_post_meta( $posts[1], 'vegetable', 'onion' );
+               add_post_meta( $posts[2], 'vegetable', 'shallot' );
+
+               $query = new WP_Query( array(
+                       'meta_query' => array(
+                               'relation' => 'OR',
+                               array(
+                                       'key' => 'vegetable',
+                                       'value' => 'onion',
+                                       'compare' => '=',
+                               ),
+                               array(
+                                       'key' => 'vegetable',
+                                       'value' => 'shallot',
+                                       'compare' => '=',
+                               ),
+                       ),
+                       'update_post_meta_cache' => false,
+                       'update_post_term_cache' => false,
+                       'fields' => 'ids',
+               ) );
+
+               $expected = array( $posts[1], $posts[2] );
+               $this->assertEqualSets( $expected, $query->posts );
+       }
+
+       /**
+        * @ticket 24093
+        */
+       public function test_meta_query_relation_or_compare_equals_different_keys() {
+               $posts = $this->factory->post->create_many( 4 );
+               add_post_meta( $posts[0], 'color', 'orange' );
+               add_post_meta( $posts[1], 'color', 'blue' );
+               add_post_meta( $posts[1], 'vegetable', 'onion' );
+               add_post_meta( $posts[2], 'vegetable', 'shallot' );
+
+               $query = new WP_Query( array(
+                       'meta_query' => array(
+                               'relation' => 'OR',
+                               array(
+                                       'key' => 'vegetable',
+                                       'value' => 'onion',
+                                       'compare' => '=',
+                               ),
+                               array(
+                                       'key' => 'color',
+                                       'value' => 'orange',
+                                       'compare' => '=',
+                               ),
+                       ),
+                       'update_post_meta_cache' => false,
+                       'update_post_term_cache' => false,
+                       'fields' => 'ids',
+               ) );
+
+               $expected = array( $posts[0], $posts[1] );
+               $this->assertEqualSets( $expected, $query->posts );
+       }
+
+       /**
+        * @ticket 24093
+        */
+       public function test_meta_query_relation_or_compare_equals_and_in() {
+               $posts = $this->factory->post->create_many( 4 );
+               add_post_meta( $posts[0], 'color', 'orange' );
+               add_post_meta( $posts[1], 'color', 'blue' );
+               add_post_meta( $posts[1], 'vegetable', 'onion' );
+               add_post_meta( $posts[2], 'vegetable', 'shallot' );
+
+               $query = new WP_Query( array(
+                       'meta_query' => array(
+                               'relation' => 'OR',
+                               array(
+                                       'key' => 'vegetable',
+                                       'value' => 'onion',
+                                       'compare' => '=',
+                               ),
+                               array(
+                                       'key' => 'color',
+                                       'value' => array( 'orange', 'green' ),
+                                       'compare' => 'IN',
+                               ),
+                       ),
+                       'update_post_meta_cache' => false,
+                       'update_post_term_cache' => false,
+                       'fields' => 'ids',
+               ) );
+
+               $expected = array( $posts[0], $posts[1] );
+               $this->assertEqualSets( $expected, $query->posts );
+       }
+
+       /**
+        * @ticket 24093
+        */
+       public function test_meta_query_relation_or_compare_equals_and_like() {
+               $posts = $this->factory->post->create_many( 4 );
+               add_post_meta( $posts[0], 'color', 'orange' );
+               add_post_meta( $posts[1], 'color', 'blue' );
+               add_post_meta( $posts[1], 'vegetable', 'onion' );
+               add_post_meta( $posts[2], 'vegetable', 'shallot' );
+
+               $query = new WP_Query( array(
+                       'meta_query' => array(
+                               'relation' => 'OR',
+                               array(
+                                       'key' => 'vegetable',
+                                       'value' => 'onion',
+                                       'compare' => '=',
+                               ),
+                               array(
+                                       'key' => 'vegetable',
+                                       'value' => 'hall',
+                                       'compare' => 'LIKE',
+                               ),
+                       ),
+                       'update_post_meta_cache' => false,
+                       'update_post_term_cache' => false,
+                       'fields' => 'ids',
+               ) );
+
+               $expected = array( $posts[1], $posts[2] );
+               $this->assertEqualSets( $expected, $query->posts );
+       }
+
+       /**
+        * @ticket 24093
+        */
+       public function test_meta_query_relation_or_compare_equals_and_between() {
+               $posts = $this->factory->post->create_many( 4 );
+               add_post_meta( $posts[0], 'number_of_colors', '2' );
+               add_post_meta( $posts[1], 'number_of_colors', '5' );
+               add_post_meta( $posts[1], 'vegetable', 'onion' );
+               add_post_meta( $posts[2], 'vegetable', 'shallot' );
+
+               $query = new WP_Query( array(
+                       'meta_query' => array(
+                               'relation' => 'OR',
+                               array(
+                                       'key' => 'vegetable',
+                                       'value' => 'shallot',
+                                       'compare' => '=',
+                               ),
+                               array(
+                                       'key' => 'number_of_colors',
+                                       'value' => array( 1, 3 ),
+                                       'compare' => 'BETWEEN',
+                                       'type' => 'SIGNED',
+                               ),
+                       ),
+                       'update_post_meta_cache' => false,
+                       'update_post_term_cache' => false,
+                       'fields' => 'ids',
+               ) );
+
+               $expected = array( $posts[0], $posts[2] );
+               $this->assertEqualSets( $expected, $query->posts );
+       }
+
+       /**
+        * @ticket 24093
+        */
+       public function test_meta_query_relation_and_compare_in_same_keys() {
+               $posts = $this->factory->post->create_many( 4 );
+               add_post_meta( $posts[0], 'color', 'orange' );
+               add_post_meta( $posts[1], 'color', 'blue' );
+               add_post_meta( $posts[1], 'vegetable', 'onion' );
+               add_post_meta( $posts[2], 'vegetable', 'shallot' );
+               add_post_meta( $posts[3], 'vegetable', 'banana' );
+               add_post_meta( $posts[3], 'vegetable', 'onion' );
+
+               $query = new WP_Query( array(
+                       'meta_query' => array(
+                               'relation' => 'AND',
+                               array(
+                                       'key' => 'vegetable',
+                                       'value' => array( 'onion', 'shallot' ),
+                                       'compare' => 'IN',
+                               ),
+                               array(
+                                       'key' => 'vegetable',
+                                       'value' => array( 'banana' ),
+                                       'compare' => 'IN',
+                               ),
+                       ),
+                       'update_post_meta_cache' => false,
+                       'update_post_term_cache' => false,
+                       'fields' => 'ids',
+               ) );
+
+               $expected = array( $posts[3] );
+               $this->assertEqualSets( $expected, $query->posts );
+       }
+
+       /**
+        * @ticket 24093
+        */
+       public function test_meta_query_relation_and_compare_in_different_keys() {
+               $posts = $this->factory->post->create_many( 4 );
+               add_post_meta( $posts[0], 'color', 'orange' );
+               add_post_meta( $posts[1], 'color', 'blue' );
+               add_post_meta( $posts[1], 'vegetable', 'onion' );
+               add_post_meta( $posts[1], 'vegetable', 'shallot' );
+               add_post_meta( $posts[2], 'vegetable', 'shallot' );
+               add_post_meta( $posts[3], 'vegetable', 'banana' );
+
+               $query = new WP_Query( array(
+                       'meta_query' => array(
+                               'relation' => 'AND',
+                               array(
+                                       'key' => 'vegetable',
+                                       'value' => array( 'onion', 'shallot' ),
+                                       'compare' => 'IN',
+                               ),
+                               array(
+                                       'key' => 'color',
+                                       'value' => array( 'blue' ),
+                                       'compare' => 'IN',
+                               ),
+                       ),
+                       'update_post_meta_cache' => false,
+                       'update_post_term_cache' => false,
+                       'fields' => 'ids',
+               ) );
+
+               $expected = array( $posts[1] );
+               $this->assertEqualSets( $expected, $query->posts );
+       }
+
+       /**
+        * @ticket 24093
+        */
+       public function test_meta_query_relation_and_compare_not_equals() {
+               $posts = $this->factory->post->create_many( 4 );
+               add_post_meta( $posts[0], 'color', 'orange' );
+               add_post_meta( $posts[1], 'color', 'blue' );
+               add_post_meta( $posts[1], 'vegetable', 'onion' );
+               add_post_meta( $posts[2], 'vegetable', 'shallot' );
+               add_post_meta( $posts[3], 'vegetable', 'banana' );
+
+               $query = new WP_Query( array(
+                       'meta_query' => array(
+                               'relation' => 'AND',
+                               array(
+                                       'key' => 'vegetable',
+                                       'value' => 'onion',
+                                       'compare' => '!=',
+                               ),
+                               array(
+                                       'key' => 'vegetable',
+                                       'value' => 'shallot',
+                                       'compare' => '!=',
+                               ),
+                       ),
+                       'update_post_meta_cache' => false,
+                       'update_post_term_cache' => false,
+                       'fields' => 'ids',
+               ) );
+
+               $expected = array( $posts[3] );
+               $this->assertEqualSets( $expected, $query->posts );
+       }
+
+       /**
+        * @ticket 24093
+        */
+       public function test_meta_query_relation_and_compare_not_equals_different_keys() {
+               $posts = $this->factory->post->create_many( 4 );
+
+               // !shallot, but orange.
+               add_post_meta( $posts[0], 'color', 'orange' );
+               add_post_meta( $posts[0], 'vegetable', 'onion' );
+
+               // !orange, but shallot.
+               add_post_meta( $posts[1], 'color', 'blue' );
+               add_post_meta( $posts[1], 'vegetable', 'shallot' );
+
+               // Neither.
+               add_post_meta( $posts[2], 'color', 'blue' );
+               add_post_meta( $posts[2], 'vegetable', 'onion' );
+
+               $query = new WP_Query( array(
+                       'meta_query' => array(
+                               'relation' => 'AND',
+                               array(
+                                       'key' => 'vegetable',
+                                       'value' => 'shallot',
+                                       'compare' => '!=',
+                               ),
+                               array(
+                                       'key' => 'color',
+                                       'value' => 'orange',
+                                       'compare' => '!=',
+                               ),
+                       ),
+                       'update_post_meta_cache' => false,
+                       'update_post_term_cache' => false,
+                       'fields' => 'ids',
+               ) );
+
+               $expected = array( $posts[2] );
+               $this->assertEqualSets( $expected, $query->posts );
+       }
+
+       /**
+        * @ticket 24093
+        */
+       public function test_meta_query_relation_and_compare_not_equals_not_in() {
+               $posts = $this->factory->post->create_many( 4 );
+               add_post_meta( $posts[0], 'color', 'orange' );
+               add_post_meta( $posts[1], 'color', 'blue' );
+               add_post_meta( $posts[1], 'vegetable', 'onion' );
+               add_post_meta( $posts[2], 'vegetable', 'shallot' );
+               add_post_meta( $posts[3], 'vegetable', 'banana' );
+
+               $query = new WP_Query( array(
+                       'meta_query' => array(
+                               'relation' => 'AND',
+                               array(
+                                       'key' => 'vegetable',
+                                       'value' => 'onion',
+                                       'compare' => '!=',
+                               ),
+                               array(
+                                       'key' => 'vegetable',
+                                       'value' => array( 'shallot' ),
+                                       'compare' => 'NOT IN',
+                               ),
+                       ),
+                       'update_post_meta_cache' => false,
+                       'update_post_term_cache' => false,
+                       'fields' => 'ids',
+               ) );
+
+               $expected = array( $posts[3] );
+               $this->assertEqualSets( $expected, $query->posts );
+       }
+
+       /**
+        * @ticket 24093
+        */
+       public function test_meta_query_relation_and_compare_not_equals_and_not_like() {
+               $posts = $this->factory->post->create_many( 4 );
+               add_post_meta( $posts[0], 'color', 'orange' );
+               add_post_meta( $posts[1], 'color', 'blue' );
+               add_post_meta( $posts[1], 'vegetable', 'onion' );
+               add_post_meta( $posts[2], 'vegetable', 'shallot' );
+               add_post_meta( $posts[3], 'vegetable', 'banana' );
+
+               $query = new WP_Query( array(
+                       'meta_query' => array(
+                               'relation' => 'AND',
+                               array(
+                                       'key' => 'vegetable',
+                                       'value' => 'onion',
+                                       'compare' => '!=',
+                               ),
+                               array(
+                                       'key' => 'vegetable',
+                                       'value' => 'hall',
+                                       'compare' => 'NOT LIKE',
+                               ),
+                       ),
+                       'update_post_meta_cache' => false,
+                       'update_post_term_cache' => false,
+                       'fields' => 'ids',
+               ) );
+
+               $expected = array( $posts[3] );
+               $this->assertEqualSets( $expected, $query->posts );
+       }
+
+       /**
</ins><span class="cx" style="display: block; padding: 0 10px">          * @ticket 23033
</span><span class="cx" style="display: block; padding: 0 10px">         * @group meta
</span><span class="cx" style="display: block; padding: 0 10px">         */
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -1040,13 +1419,13 @@
</span><span class="cx" style="display: block; padding: 0 10px">                $post_id6 = $this->factory->post->create();
</span><span class="cx" style="display: block; padding: 0 10px">                add_post_meta( $post_id6, 'baz', 0 );
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-                $posts = get_posts( array( 'meta_key' => 'foo', 'meta_value' => '0' ) );
-               $this->assertEquals( 1, count ( $posts ) );
-               foreach ( $posts as $post ) {
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+         $q = new WP_Query( array( 'meta_key' => 'foo', 'meta_value' => '0' ) );
+               $this->assertEquals( 1, count ( $q->posts ) );
+               foreach ( $q->posts as $post ) {
</ins><span class="cx" style="display: block; padding: 0 10px">                         $this->assertInstanceOf( 'WP_Post', $post );
</span><span class="cx" style="display: block; padding: 0 10px">                        $this->assertEquals( 'raw', $post->filter );
</span><span class="cx" style="display: block; padding: 0 10px">                }
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-                $this->assertEquals( $post_id, $posts[0]->ID );
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+         $this->assertEquals( $post_id, $q->posts[0]->ID );
</ins><span class="cx" style="display: block; padding: 0 10px"> 
</span><span class="cx" style="display: block; padding: 0 10px">                $posts = get_posts( array( 'meta_key' => 'bar', 'meta_value' => '0' ) );
</span><span class="cx" style="display: block; padding: 0 10px">                $this->assertEquals( 2, count ( $posts ) );
</span></span></pre>
</div>
</div>

</body>
</html>