diff --git src/wp-includes/meta.php src/wp-includes/meta.php
index e3c43cf..9244e70 100644
--- src/wp-includes/meta.php
+++ src/wp-includes/meta.php
@@ -849,26 +849,58 @@ function get_meta_sql( $meta_query, $type, $primary_table, $primary_id_column, $
 }
 
 /**
- * Container class for a multiple metadata query
+ * Class for generating SQL clauses that filter a primary query according to metadata keys and values.
+ *
+ * WP_Meta_Query is a helper that allows primary query classes, such as WP_Query
+ * and WP_User_Query, to filter their results by object metadata, by generating
+ * JOIN and WHERE subclauses to be attached to the primary SQL query string.
+ *
+ * The fundamental unit of a meta query is the "first-order clause", an array
+ * of arguments of the following form:
+ *     array(
+ *         'key' => 'your_meta_key',
+ *         'value' => 'Some value',
+ *         'compare' => '=',
+ *         'type' => 'CHAR',
+ *      )
+ * (See the documentation for {@link WP_Meta_Query::__construct()} for more
+ * details on accepted paramaters.) WP_Meta_Query accepts an array of these
+ * first-order clauses, which can be joined by a 'relation' of 'AND' or 'OR.
+ *
+ * Furthermore, these arrays can be nested and combined using multiple values
+ * of 'relation', to generate queries of arbitrary complexity. For example:
+ *     array(
+ *         'relation' => 'OR',
+ *         array(
+ *             'key' => 'city',
+ *             'value' => 'New York',
+ *         ),
+ *         array(
+ *             'relation' => 'AND',
+ *             array(
+ *                 'key' => 'state',
+ *                 'value' => 'Massachusetts',
+ *             ),
+ *             array(
+ *                 'key' => 'city'
+ *                 'value' => 'Boston',
+ *                 'compare' => '!=',
+ *             ),
+ *         ),
+ *     )
+ * will return items that are either labeled New York, or labeled Massachusetts
+ * but not Boston.
  *
  * @since 3.2.0
  */
 class WP_Meta_Query {
 	/**
-	* List of metadata queries. A single query is an associative array:
-	* - 'key' string The meta key
-	* - 'value' string|array The meta value
-	* - 'compare' (optional) string How to compare the key to the value.
-	*              Possible values: '=', '!=', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN',
-	*              'BETWEEN', 'NOT BETWEEN', 'REGEXP', 'NOT REGEXP', 'RLIKE'.
-	*              Default: '='
-	* - 'type' string (optional) The type of the value.
-	*              Possible values: 'NUMERIC', 'BINARY', 'CHAR', 'DATE', 'DATETIME', 'DECIMAL', 'SIGNED', 'TIME', 'UNSIGNED'.
-	*              Default: 'CHAR'
+	* Array of metadata queries.
 	*
 	* @since 3.2.0
 	* @access public
 	* @var array
+	* @see WP_Meta_Query::__construct() for description of params.
 	*/
 	public $queries = array();
 
@@ -882,9 +914,66 @@ class WP_Meta_Query {
 	public $relation;
 
 	/**
-	 * Constructor
+	 * Database table to query for the metadata.
+	 *
+	 * @access public
+	 * @var string
+	 */
+	public $meta_table;
+
+	/**
+	 * Column in meta_table that represents the ID of the object the metadata belongs to.
 	 *
-	 * @param array $meta_query (optional) A meta query
+	 * @access public
+	 * @var string
+	 */
+	public $meta_id_column;
+
+	/**
+	 * Database table that where the metadata's objects are stored (eg $wpdb->users).
+	 *
+	 * @access public
+	 * @var string
+	 */
+	public $primary_table;
+
+	/**
+	 * Column in primary_table that represents the ID of the object.
+	 *
+	 * @access public
+	 * @var string
+	 */
+	public $primary_id_column;
+
+	/**
+	 * A flat list of table aliases used in JOIN clauses.
+	 *
+	 * @since 4.1.0
+	 * @access protected
+	 * @var array
+	 */
+	protected $table_aliases = array();
+
+	/**
+	 * Constructor.
+	 *
+	 * @param array $meta_query {
+	 *     Meta query clauses.
+	 *     @type string $relation Optional. The MySQL keyword used to join
+	 *                            the clauses of the query. (AND|OR)
+	 *     @type array {
+	 *         A first-order clause, or another fully-formed meta query.
+	 *         Parameters for first-order clauses are described here. All are optional.
+	 *         @type string $key     Meta key to filter by.
+	 *         @type string $value   Meta value to filter by.
+	 *         @type string $compare MySQL operator used for comparing the $value.
+	 *                               Default: 'IN when $value is an array, otherwise '='.
+	 *                               (=|!=|>|>=|<|<=|LIKE|NOT LIKE|IN|NOT IN|BETWEEN|NOT BETWEEN|REGEXP|NOT REGEXP|RLIKE)
+	 *         @type string $type    MySQL data type that the meta_value column will be CAST to
+	 *                               for comparisons. Default: 'CHAR'.
+	 *                               (NUMERIC|BINARY|CHAR|DATE|DATETIME|DECIMAL|SIGNED|TIME|UNSIGNED)
+	 *     }
+	 * }
 	 */
 	public function __construct( $meta_query = false ) {
 		if ( !$meta_query )
@@ -896,14 +985,80 @@ class WP_Meta_Query {
 			$this->relation = 'AND';
 		}
 
-		$this->queries = array();
+		$this->queries = $this->sanitize_query( $meta_query );
+	}
+
+	/**
+	 * Ensure that the meta_query argument passed to the class constructor is well-formed.
+	 *
+	 * Eliminates empty items and ensures that a 'relation' is set.
+	 *
+	 * @param  array $queries Array of query clauses.
+	 * @return array Sanitized array of query clauses.
+	 */
+	public function sanitize_query( $queries ) {
+		$clean_queries = array();
+
+		if ( ! is_array( $queries ) ) {
+			return $clean_queries;
+		}
+
+		foreach ( $queries as $key => $query ) {
+			if ( 'relation' === $key ) {
+				$relation = $query;
+
+			// First-order clause.
+			} else if ( $this->is_first_order_clause( $query ) ) {
+				$clean_queries[] = $query;
+
+			// Otherwise, it's a nested query.
+			} else {
+				$cleaned_query = $this->sanitize_query( $query );
+
+				if ( ! empty( $cleaned_query ) ) {
+					$clean_queries[] = $cleaned_query;
+				}
+			}
+		}
+
+		if ( empty( $clean_queries ) ) {
+			return $clean_queries;
+		}
 
-		foreach ( $meta_query as $key => $query ) {
-			if ( ! is_array( $query ) )
-				continue;
+		// Sanitize the 'relation' key provided in the query.
+		if ( isset( $relation ) && 'OR' === strtoupper( $relation ) ) {
+			$clean_queries['relation'] = 'OR';
 
-			$this->queries[] = $query;
+		/*
+		 * If there is only a single clause, call the relation 'OR'.
+		 * This value will not actually be used to join clauses, but it
+		 * simplifies the logic around combining key-only queries.
+		 */
+		} else if ( 1 === count( $clean_queries ) ) {
+			$clean_queries['relation'] = 'OR';
+
+		// Default to AND.
+		} else {
+			$clean_queries['relation'] = 'AND';
 		}
+
+		return $clean_queries;
+	}
+
+	/**
+	 * Determine whether a query clause is first-order.
+	 *
+	 * A first-order meta query clause is one that has either a 'key' or
+	 * a 'value' array key.
+	 *
+	 * @since 4.1.0
+	 * @access protected
+	 *
+	 * @param  array $query Meta query arguments.
+	 * @return bool
+	 */
+	protected function is_first_order_clause( $query ) {
+		return isset( $query['key'] ) || isset( $query['value'] );
 	}
 
 	/**
@@ -963,120 +1118,258 @@ class WP_Meta_Query {
 	 * @since 3.2.0
 	 * @access public
 	 *
-	 * @param string $type Type of meta
-	 * @param string $primary_table
-	 * @param string $primary_id_column
-	 * @param object $context (optional) The main query object
-	 * @return array( 'join' => $join_sql, 'where' => $where_sql )
+	 * @param  string $type              Type of meta, eg 'user', 'post'.
+	 * @param  string $primary_table     Database table where the object being
+	 *                                   filtered is stored (eg wp_users).
+	 * @param  string $primary_id_column ID column for the filtered object in $primary_table.
+	 * @param  object $context           Optional. The main query object.
+	 * @return array {
+	 *	@type string $join SQL fragment to append to the main JOIN clause.
+	 *	@type string $where SQL fragment to append to the main WHERE clause.
+	 * }
 	 */
 	public function get_sql( $type, $primary_table, $primary_id_column, $context = null ) {
 		global $wpdb;
 
-		if ( ! $meta_table = _get_meta_table( $type ) )
+		if ( ! $meta_table = _get_meta_table( $type ) ) {
 			return false;
+		}
 
-		$meta_id_column = sanitize_key( $type . '_id' );
+		$this->meta_table     = $meta_table;
+		$this->meta_id_column = sanitize_key( $type . '_id' );
 
-		$join = array();
-		$where = array();
+		$this->primary_table     = $primary_table;
+		$this->primary_id_column = $primary_id_column;
 
-		$key_only_queries = array();
-		$queries = array();
+		$sql = $this->get_sql_clauses();
 
-		// Split out the queries with empty arrays as value
-		foreach ( $this->queries as $k => $q ) {
-			if ( isset( $q['value'] ) && is_array( $q['value'] ) && empty( $q['value'] ) ) {
-				$key_only_queries[$k] = $q;
-				unset( $this->queries[$k] );
-			}
+		/**
+		 * Filter the meta query's generated SQL.
+		 *
+		 * @since 3.1.0
+		 *
+		 * @param array $args {
+		 *     An array of arguments.
+		 *
+		 *     @type array  $clauses           Array containing the query's JOIN and WHERE clauses.
+		 *     @type array  $queries           Array of meta queries.
+		 *     @type string $type              Type of meta.
+		 *     @type string $primary_table     Primary table.
+		 *     @type string $primary_id_column Primary column ID.
+		 *     @type object $context           The main query object.
+		 * }
+		 */
+		return apply_filters_ref_array( 'get_meta_sql', array( $sql, $this->queries, $type, $primary_table, $primary_id_column, $context ) );
+	}
+
+	/**
+	 * Generate SQL clauses to be appended to a main query.
+	 *
+	 * Called by the public {@link WP_Meta_Query::get_sql()}, this method
+	 * is abstracted out to maintain parity with the other Query classes.
+	 *
+	 * @since 4.1.0
+	 * @access protected
+	 *
+	 * @return array {
+	 *	@type string $join SQL fragment to append to the main JOIN clause.
+	 *	@type string $where SQL fragment to append to the main WHERE clause.
+	 * }
+	 */
+	protected function get_sql_clauses() {
+		$sql = $this->get_sql_for_query( $this->queries );
+
+		if ( ! empty( $sql['where'] ) ) {
+			$sql['where'] = ' AND ' . "\n" . $sql['where'] . "\n";
 		}
 
-		// Split out the meta_key only queries (we can only do this for OR)
-		if ( 'OR' == $this->relation ) {
-			foreach ( $this->queries as $k => $q ) {
-				if ( ( empty( $q['compare'] ) || 'NOT EXISTS' != $q['compare'] ) && ! array_key_exists( 'value', $q ) && ! empty( $q['key'] ) )
-					$key_only_queries[$k] = $q;
-				else
-					$queries[$k] = $q;
+		return $sql;
+	}
+
+	/**
+	 * Generate SQL clauses for a single query array.
+	 *
+	 * If nested subqueries are found, this method recurses the tree to
+	 * produce the properly nested SQL.
+	 *
+	 * @since 4.1.0
+	 * @access protected
+	 *
+	 * @param  array $query Query to parse.
+	 * @param  int   $depth Optional. Number of tree levels deep we
+	 *                      currently are. Used to calculate indentation.
+	 * @return array {
+	 *	@type string $join SQL fragment to append to the main JOIN clause.
+	 *	@type string $where SQL fragment to append to the main WHERE clause.
+	 * }
+	 */
+	protected function get_sql_for_query( $query, $depth = 0 ) {
+		$sql_chunks = array(
+			'join'  => array(),
+			'where' => array(),
+		);
+
+		$sql = array(
+			'join'  => '',
+			'where' => '',
+		);
+
+		$indent = '';
+		for ( $i = 0; $i < $depth; $i++ ) {
+			$indent .= "\t";
+		}
+
+		foreach ( $query as $key => $clause ) {
+			if ( 'relation' === $key ) {
+				$relation = $query['relation'];
+			} else if ( is_array( $clause ) ) {
+
+				// This is a first-order clause.
+				if ( $this->is_first_order_clause( $clause ) ) {
+					$clause_sql = $this->get_sql_for_clause( $clause, $query );
+
+					$where_count = count( $clause_sql['where'] );
+					if ( ! $where_count ) {
+						$sql_chunks['where'][] = '';
+					} else if ( 1 === $where_count ) {
+						$sql_chunks['where'][] = $clause_sql['where'][0];
+					} else {
+						$sql_chunks['where'][] = '( ' . implode( ' AND ', $clause_sql['where'] ) . ' )';
+					}
+
+					$sql_chunks['join'] = array_merge( $sql_chunks['join'], $clause_sql['join'] );
+				// This is a subquery, so we recurse.
+				} else {
+					$clause_sql = $this->get_sql_for_query( $clause, $depth + 1 );
+
+					$sql_chunks['where'][] = $clause_sql['where'];
+					$sql_chunks['join'][]  = $clause_sql['join'];
+				}
 			}
-		} else {
-			$queries = $this->queries;
 		}
 
-		// Specify all the meta_key only queries in one go
-		if ( $key_only_queries ) {
-			$join[]  = "INNER JOIN $meta_table ON $primary_table.$primary_id_column = $meta_table.$meta_id_column";
+		// Filter to remove empties.
+		$sql_chunks['join']  = array_filter( $sql_chunks['join'] );
+		$sql_chunks['where'] = array_filter( $sql_chunks['where'] );
 
-			foreach ( $key_only_queries as $key => $q )
-				$where["key-only-$key"] = $wpdb->prepare( "$meta_table.meta_key = %s", trim( $q['key'] ) );
+		if ( empty( $relation ) ) {
+			$relation = 'AND';
 		}
 
-		foreach ( $queries as $k => $q ) {
-			$meta_key = isset( $q['key'] ) ? trim( $q['key'] ) : '';
-			$meta_type = $this->get_cast_for_type( isset( $q['type'] ) ? $q['type'] : '' );
+		// Filter duplicate JOIN clauses and combine into a single string.
+		if ( ! empty( $sql_chunks['join'] ) ) {
+			$sql['join'] = implode( ' ', array_unique( $sql_chunks['join'] ) );
+		}
 
-			if ( array_key_exists( 'value', $q ) && is_null( $q['value'] ) )
-				$q['value'] = '';
+		// Generate a single WHERE clause with proper brackets and indentation.
+		if ( ! empty( $sql_chunks['where'] ) ) {
+			$sql['where'] = '( ' . "\n\t" . $indent . implode( ' ' . "\n\t" . $indent . $relation . ' ' . "\n\t" . $indent, $sql_chunks['where'] ) . "\n" . $indent . ')' . "\n";
+		}
 
-			$meta_value = isset( $q['value'] ) ? $q['value'] : null;
+		return $sql;
+	}
 
-			if ( isset( $q['compare'] ) )
-				$meta_compare = strtoupper( $q['compare'] );
-			else
-				$meta_compare = is_array( $meta_value ) ? 'IN' : '=';
+	/**
+	 * Generate SQL JOIN and WHERE clauses for a first-order query clause.
+	 *
+	 * "First-order" means that it's an array with a 'key' or 'value'.
+	 *
+	 * @param  array $clause       Query clause.
+	 * @param  array $parent_query Parent query array.
+	 * @return array {
+	 *	@type string $join SQL fragment to append to the main JOIN clause.
+	 *	@type string $where SQL fragment to append to the main WHERE clause.
+	 * }
+	 */
+	public function get_sql_for_clause( $clause, $parent_query ) {
+		global $wpdb;
 
-			if ( ! in_array( $meta_compare, array(
-				'=', '!=', '>', '>=', '<', '<=',
-				'LIKE', 'NOT LIKE',
-				'IN', 'NOT IN',
-				'BETWEEN', 'NOT BETWEEN',
-				'NOT EXISTS',
-				'REGEXP', 'NOT REGEXP', 'RLIKE'
-			) ) )
-				$meta_compare = '=';
+		$sql_chunks = array(
+			'where' => array(),
+			'join' => array(),
+		);
 
-			$i = count( $join );
-			$alias = $i ? 'mt' . $i : $meta_table;
+		$i = count( $this->table_aliases );
+		$alias = $i ? 'mt' . $i : $this->meta_table;
 
-			if ( 'NOT EXISTS' == $meta_compare ) {
-				$join[$i]  = "LEFT JOIN $meta_table";
-				$join[$i] .= $i ? " AS $alias" : '';
-				$join[$i] .= " ON ($primary_table.$primary_id_column = $alias.$meta_id_column AND $alias.meta_key = '$meta_key')";
+		if ( isset( $clause['compare'] ) ) {
+			$meta_compare = strtoupper( $clause['compare'] );
+		} else {
+			$meta_compare = isset( $clause['value'] ) && is_array( $clause['value'] ) ? 'IN' : '=';
+		}
 
-				$where[$k] = ' ' . $alias . '.' . $meta_id_column . ' IS NULL';
+		if ( ! in_array( $meta_compare, array(
+			'=', '!=', '>', '>=', '<', '<=',
+			'LIKE', 'NOT LIKE',
+			'IN', 'NOT IN',
+			'BETWEEN', 'NOT BETWEEN',
+			'EXISTS', 'NOT EXISTS',
+			'REGEXP', 'NOT REGEXP', 'RLIKE'
+		) ) ) {
+			$meta_compare = '=';
+		}
 
-				continue;
+		/*
+		 * 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'] ) )
+		) ) {
+
+			$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'] ) );
+
+		// 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;
+
+			$sql_chunks['where'][] = $alias . '.' . $this->meta_id_column . ' IS NULL';
+
+		// 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;
+
+			$sql_chunks['where'][] = $wpdb->prepare( $alias . '.meta_key = %s', trim( $clause['key'] ) );
+
+		// 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)";
+			$sql_chunks['join'][] = $join;
+
+			if ( ! empty( $clause['key'] ) ) {
+				$sql_chunks['where'][] = $wpdb->prepare( "$alias.meta_key = %s", trim( $clause['key'] ) );
 			}
 
-			$join[$i]  = "INNER JOIN $meta_table";
-			$join[$i] .= $i ? " AS $alias" : '';
-			$join[$i] .= " ON ($primary_table.$primary_id_column = $alias.$meta_id_column)";
-
-			$where[$k] = '';
-			if ( !empty( $meta_key ) )
-				$where[$k] = $wpdb->prepare( "$alias.meta_key = %s", $meta_key );
+			$meta_type = $this->get_cast_for_type( isset( $clause['type'] ) ? $clause['type'] : '' );
 
-			if ( is_null( $meta_value ) ) {
-				if ( empty( $where[$k] ) )
-					unset( $join[$i] );
-				continue;
-			}
+			$meta_value = isset( $clause['value'] ) ? $clause['value'] : '';
 
 			if ( in_array( $meta_compare, array( 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN' ) ) ) {
-				if ( ! is_array( $meta_value ) )
+				if ( ! is_array( $meta_value ) ) {
 					$meta_value = preg_split( '/[,\s]+/', $meta_value );
-
-				if ( empty( $meta_value ) ) {
-					unset( $join[$i] );
-					continue;
 				}
 			} else {
 				$meta_value = trim( $meta_value );
 			}
 
-			if ( 'IN' == substr( $meta_compare, -2) ) {
+			if ( 'IN' == substr( $meta_compare, -2 ) ) {
 				$meta_compare_string = '(' . substr( str_repeat( ',%s', count( $meta_value ) ), 1 ) . ')';
-			} elseif ( 'BETWEEN' == substr( $meta_compare, -7) ) {
+			} 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 ) {
@@ -1086,40 +1379,20 @@ class WP_Meta_Query {
 				$meta_compare_string = '%s';
 			}
 
-			if ( ! empty( $where[$k] ) )
-				$where[$k] .= ' AND ';
-
-			$where[$k] = ' (' . $where[$k] . $wpdb->prepare( "CAST($alias.meta_value AS {$meta_type}) {$meta_compare} {$meta_compare_string})", $meta_value );
+			$sql_chunks['where'][] = $wpdb->prepare( "CAST($alias.meta_value AS {$meta_type}) {$meta_compare} {$meta_compare_string}", $meta_value );
 		}
 
-		$where = array_filter( $where );
-
-		if ( empty( $where ) )
-			$where = '';
-		else
-			$where = ' AND (' . implode( "\n{$this->relation} ", $where ) . ' )';
+		/*
+		 * Multiple WHERE clauses (for meta_key and meta_value) should
+		 * be joined in parentheses.
+		 */
+		if ( 1 < count( $sql_chunks['where'] ) ) {
+			$sql_chunks['where'] = array( '( ' . implode( ' AND ', $sql_chunks['where'] ) . ' )' );
+		}
 
-		$join = implode( "\n", $join );
-		if ( ! empty( $join ) )
-			$join = ' ' . $join;
+		$this->table_aliases[] = $alias;
 
-		/**
-		 * Filter the meta query's generated SQL.
-		 *
-		 * @since 3.1.0
-		 *
-		 * @param array $args {
-		 *     An array of arguments.
-		 *
-		 *     @type array  $clauses           Array containing the query's JOIN and WHERE clauses.
-		 *     @type array  $queries           Array of meta queries.
-		 *     @type string $type              Type of meta.
-		 *     @type string $primary_table     Primary table.
-		 *     @type string $primary_id_column Primary column ID.
-		 *     @type object $context           The main query object.
-		 * }
-		 */
-		return apply_filters_ref_array( 'get_meta_sql', array( compact( 'join', 'where' ), $this->queries, $type, $primary_table, $primary_id_column, $context ) );
+		return $sql_chunks;
 	}
 }
 
diff --git tests/phpunit/tests/meta/query.php tests/phpunit/tests/meta/query.php
index fb2a1cc..390ccc9 100644
--- tests/phpunit/tests/meta/query.php
+++ tests/phpunit/tests/meta/query.php
@@ -40,7 +40,7 @@ class Tests_Meta_Query extends WP_UnitTestCase {
 			array(),
 		) );
 
-		$this->assertSame( array( array() ), $query->queries );
+		$this->assertSame( array(), $query->queries );
 	}
 
 	/**
@@ -153,19 +153,44 @@ class Tests_Meta_Query extends WP_UnitTestCase {
 		$query = new WP_Meta_Query();
 
 		// just meta_value
-		$query->parse_query_vars( array( 'meta_key' => 'abc' ) );
-
-		$this->assertEquals( array( array( 'key' => 'abc' ) ), $query->queries );
+		$expected = array(
+			'relation' => 'OR',
+			array(
+				'key' => 'abc',
+			),
+		);
+		$query->parse_query_vars( array(
+			'meta_key' => 'abc',
+		) );
+		$this->assertEquals( $expected, $query->queries );
 
 		// meta_key & meta_value
-		$query->parse_query_vars( array( 'meta_key' => 'abc', 'meta_value' => 'def' ) );
-
-		$this->assertEquals( array( array( 'key' => 'abc', 'value' => 'def' ) ), $query->queries );
+		$expected = array(
+			'relation' => 'OR',
+			array(
+				'key' => 'abc',
+				'value' => 'def',
+			),
+		);
+		$query->parse_query_vars( array(
+			'meta_key' => 'abc',
+			'meta_value' => 'def',
+		) );
+		$this->assertEquals( $expected, $query->queries );
 
 		// meta_compare
-		$query->parse_query_vars( array( 'meta_key' => 'abc', 'meta_compare' => '=>' ) );
-
-		$this->assertEquals( array( array( 'key' => 'abc', 'compare' => '=>' ) ), $query->queries );
+		$expected = array(
+			'relation' => 'OR',
+			array(
+				'key' => 'abc',
+				'compare' => '=>',
+			),
+		);
+		$query->parse_query_vars( array(
+			'meta_key' => 'abc',
+			'meta_compare' => '=>',
+		) );
+		$this->assertEquals( $expected, $query->queries );
 	}
 
 	/**
@@ -202,6 +227,229 @@ class Tests_Meta_Query extends WP_UnitTestCase {
 		$this->assertEquals( 'CHAR', $query->get_cast_for_type( 'ANYTHING ELSE' ) );
 	}
 
+	public function test_sanitize_query_single_query() {
+		$expected = array(
+			'relation' => 'OR',
+			array(
+				'key' => 'foo',
+				'value' => 'bar',
+			),
+		);
+
+		$q = new WP_Meta_Query();
+		$found = $q->sanitize_query( array(
+			array(
+				'key' => 'foo',
+				'value' => 'bar',
+			),
+		) );
+
+		$this->assertEquals( $expected, $found );
+	}
+
+	public function test_sanitize_query_multiple_first_order_queries_relation_default() {
+		$expected = array(
+			'relation' => 'AND',
+			array(
+				'key' => 'foo',
+				'value' => 'bar',
+			),
+			array(
+				'key' => 'foo2',
+				'value' => 'bar2',
+			),
+		);
+
+		$q = new WP_Meta_Query();
+		$found = $q->sanitize_query( array(
+			array(
+				'key' => 'foo',
+				'value' => 'bar',
+			),
+			array(
+				'key' => 'foo2',
+				'value' => 'bar2',
+			),
+		) );
+
+		$this->assertEquals( $expected, $found );
+	}
+
+	public function test_sanitize_query_multiple_first_order_queries_relation_or() {
+		$expected = array(
+			'relation' => 'OR',
+			array(
+				'key' => 'foo',
+				'value' => 'bar',
+			),
+			array(
+				'key' => 'foo2',
+				'value' => 'bar2',
+			),
+		);
+
+		$q = new WP_Meta_Query();
+		$found = $q->sanitize_query( array(
+			'relation' => 'OR',
+			array(
+				'key' => 'foo',
+				'value' => 'bar',
+			),
+			array(
+				'key' => 'foo2',
+				'value' => 'bar2',
+			),
+		) );
+
+		$this->assertEquals( $expected, $found );
+	}
+
+	public function test_sanitize_query_multiple_first_order_queries_relation_or_lowercase() {
+		$expected = array(
+			'relation' => 'OR',
+			array(
+				'key' => 'foo',
+				'value' => 'bar',
+			),
+			array(
+				'key' => 'foo2',
+				'value' => 'bar2',
+			),
+		);
+
+		$q = new WP_Meta_Query();
+		$found = $q->sanitize_query( array(
+			'relation' => 'or',
+			array(
+				'key' => 'foo',
+				'value' => 'bar',
+			),
+			array(
+				'key' => 'foo2',
+				'value' => 'bar2',
+			),
+		) );
+
+		$this->assertEquals( $expected, $found );
+	}
+
+	public function test_sanitize_query_multiple_first_order_queries_invalid_relation() {
+		$expected = array(
+			'relation' => 'AND',
+			array(
+				'key' => 'foo',
+				'value' => 'bar',
+			),
+			array(
+				'key' => 'foo2',
+				'value' => 'bar2',
+			),
+		);
+
+		$q = new WP_Meta_Query();
+		$found = $q->sanitize_query( array(
+			'relation' => 'FOO',
+			array(
+				'key' => 'foo',
+				'value' => 'bar',
+			),
+			array(
+				'key' => 'foo2',
+				'value' => 'bar2',
+			),
+		) );
+
+		$this->assertEquals( $expected, $found );
+	}
+
+	public function test_sanitize_query_single_query_which_is_a_nested_query() {
+		$expected = array(
+			'relation' => 'OR',
+			array(
+				'relation' => 'AND',
+				array(
+					'key' => 'foo',
+					'value' => 'bar',
+				),
+				array(
+					'key' => 'foo2',
+					'value' => 'bar2',
+				),
+			)
+		);
+
+		$q = new WP_Meta_Query();
+		$found = $q->sanitize_query( array(
+			array(
+				array(
+					'key' => 'foo',
+					'value' => 'bar',
+				),
+				array(
+					'key' => 'foo2',
+					'value' => 'bar2',
+				),
+			),
+		) );
+
+		$this->assertEquals( $expected, $found );
+	}
+
+	public function test_sanitize_query_multiple_nested_queries() {
+		$expected = array(
+			'relation' => 'OR',
+			array(
+				'relation' => 'AND',
+				array(
+					'key' => 'foo',
+					'value' => 'bar',
+				),
+				array(
+					'key' => 'foo2',
+					'value' => 'bar2',
+				),
+			),
+			array(
+				'relation' => 'AND',
+				array(
+					'key' => 'foo3',
+					'value' => 'bar3',
+				),
+				array(
+					'key' => 'foo4',
+					'value' => 'bar4',
+				),
+			),
+		);
+
+		$q = new WP_Meta_Query();
+		$found = $q->sanitize_query( array(
+			'relation' => 'OR',
+			array(
+				array(
+					'key' => 'foo',
+					'value' => 'bar',
+				),
+				array(
+					'key' => 'foo2',
+					'value' => 'bar2',
+				),
+			),
+			array(
+				array(
+					'key' => 'foo3',
+					'value' => 'bar3',
+				),
+				array(
+					'key' => 'foo4',
+					'value' => 'bar4',
+				),
+			),
+		) );
+
+		$this->assertEquals( $expected, $found );
+	}
+
 	/**
 	 * Invalid $type will fail to get a table from _get_meta_table()
 	 */
@@ -229,7 +477,7 @@ class Tests_Meta_Query extends WP_UnitTestCase {
 		$sql = $query->get_sql( 'post', $wpdb->posts, 'ID', $this );
 
 		// We should have 2 joins - one for my_first_key and one for my_second_key
-		$this->assertEquals( 2, substr_count( $sql['join'], 'INNER JOIN' ) );
+		$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'" ) );
@@ -247,7 +495,7 @@ class Tests_Meta_Query extends WP_UnitTestCase {
 		) );
 		$sql = $query->get_sql( 'post', $wpdb->posts, 'ID', $this );
 
-		$this->assertEquals( 1, substr_count( $sql['where'], "CAST($wpdb->postmeta.meta_value AS CHAR) = '')" ) );
+		$this->assertEquals( 1, substr_count( $sql['where'], "CAST($wpdb->postmeta.meta_value AS CHAR) = ''" ) );
 	}
 
 	/**
@@ -558,7 +806,9 @@ class Tests_Meta_Query extends WP_UnitTestCase {
 		) );
 
 		$sql = $query->get_sql( 'post', $wpdb->posts, 'ID', $this );
-		$this->assertContains( "{$wpdb->postmeta}.meta_key = 'exclude'\nOR", $sql['where'] );
+
+		// Use regex because we don't care about the whitespace before OR.
+		$this->assertRegExp( "/{$wpdb->postmeta}\.meta_key = \'exclude\'\s+OR/", $sql['where'] );
 		$this->assertNotContains( "{$wpdb->postmeta}.post_id IS NULL", $sql['where'] );
 	}
 }
diff --git tests/phpunit/tests/post/query.php tests/phpunit/tests/post/query.php
index 0539edc..dbe157e 100644
--- tests/phpunit/tests/post/query.php
+++ tests/phpunit/tests/post/query.php
@@ -1408,6 +1408,89 @@ class Tests_Post_Query extends WP_UnitTestCase {
 		$this->assertEquals( array( $p1, $p2 ), $q->posts );
 	}
 
+	public function test_meta_query_nested() {
+		$p1 = $this->factory->post->create();
+		$p2 = $this->factory->post->create();
+		$p3 = $this->factory->post->create();
+
+		add_post_meta( $p1, 'foo', 'bar' );
+		add_post_meta( $p2, 'foo2', 'bar' );
+		add_post_meta( $p3, 'foo2', 'bar' );
+		add_post_meta( $p3, 'foo3', 'bar' );
+
+		$query = new WP_Query( array(
+			'update_post_meta_cache' => false,
+			'update_term_meta_cache' => false,
+			'fields' => 'ids',
+			'meta_query' => array(
+				'relation' => 'OR',
+				array(
+					'key' => 'foo',
+					'value' => 'bar',
+				),
+				array(
+					'relation' => 'AND',
+					array(
+						'key' => 'foo2',
+						'value' => 'bar',
+					),
+					array(
+						'key' => 'foo3',
+						'value' => 'bar',
+					),
+				),
+			),
+		) );
+
+		$expected = array( $p1, $p3 );
+		$this->assertEqualSets( $expected, $query->posts );
+	}
+
+	public function test_meta_query_nested_two_levels_deep() {
+		$p1 = $this->factory->post->create();
+		$p2 = $this->factory->post->create();
+		$p3 = $this->factory->post->create();
+
+		add_post_meta( $p1, 'foo', 'bar' );
+		add_post_meta( $p3, 'foo2', 'bar' );
+		add_post_meta( $p3, 'foo3', 'bar' );
+		add_post_meta( $p3, 'foo4', 'bar' );
+
+		$query = new WP_Query( array(
+			'update_post_meta_cache' => false,
+			'update_term_meta_cache' => false,
+			'fields' => 'ids',
+			'meta_query' => array(
+				'relation' => 'OR',
+				array(
+					'key' => 'foo',
+					'value' => 'bar',
+				),
+				array(
+					'relation' => 'OR',
+					array(
+						'key' => 'foo2',
+						'value' => 'bar',
+					),
+					array(
+						'relation' => 'AND',
+						array(
+							'key' => 'foo3',
+							'value' => 'bar',
+						),
+						array(
+							'key' => 'foo4',
+							'value' => 'bar',
+						),
+					),
+				),
+			),
+		) );
+
+		$expected = array( $p1, $p3 );
+		$this->assertEqualSets( $expected, $query->posts );
+	}
+
 	/**
 	 * @ticket 20604
 	 * @group taxonomy
