Opened 8 months ago
Last modified 3 weeks ago
#22096 accepted defect (bug)
IN meta_query with empty array as meta_value results in invalid database query
| Reported by: |
|
Owned by: |
|
|---|---|---|---|
| Priority: | normal | Milestone: | 3.6 |
| Component: | Query | Version: | 3.1.3 |
| Severity: | normal | Keywords: | has-patch |
| Cc: | batmoo, erick@…, johnjamesjacoby |
Description
If you do an IN meta_query and pass in an empty array to the value, the INNER JOIN clause for the postmeta table isn't added, which results in an invalid query:
new WP_Query( array(
'meta_query' => array( array( 'key' => 'abc', 'value' => array(), 'compare' => 'IN' ) )
) );
This results in an error like so:
WordPress database error: [Unknown column 'wp_postmeta.meta_key' in 'where clause'] SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE 1=1 AND wp_posts.post_type = 'post' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private') AND (wp_postmeta.meta_key = 'abc' ) GROUP BY wp_posts.ID ORDER BY wp_posts.post_date DESC LIMIT 0, 5
Attachments (1)
Change History (10)
comment:3
SergeyBiryukov — 8 months ago
- Version changed from 3.4 to 3.1.3
Caused by line 520 of [17746].
wonderboymusic — 7 months ago
comment:4
wonderboymusic — 7 months ago
- Keywords has-patch added
- Milestone changed from Awaiting Review to Future Release
- Owner set to wonderboymusic
- Status changed from new to accepted
We need to add WP_Meta_Query::clean_query maybe - patch passes Unit Tests
comment:5
wonderboymusic — 4 months ago
- Milestone changed from Future Release to 3.6
This patch still applies cleanly, works, etc (I have no recollection of actually writing this patch)
Another example, this time when you combine a 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN' with an empty value and another valid IN:
new WP_Query( array(
'meta_query' => array(
'relation' => 'AND',
array( 'key' => 'key1', 'value' => array( 'value1', 'value1b' ), 'compare' => 'IN' ),
array( 'key' => 'key2', 'value' => array(), 'compare' => 'NOT IN' )
)
) );
results in:
SELECT SQL_CALC_FOUND_ROWS wp_15797879_posts.ID FROM wp_15797879_posts INNER JOIN wp_15797879_postmeta ON (wp_15797879_posts.ID = wp_15797879_postmeta.post_id) WHERE 1=1 AND wp_15797879_posts.post_type = \'post\' AND (wp_15797879_posts.post_status = \'publish\') AND ( (wp_15797879_postmeta.meta_key = 'key1' AND CAST(wp_15797879_postmeta.meta_value AS CHAR) IN (\'value1\',\'value1b\')) AND mt1.meta_key = 'key2' ) GROUP BY wp_15797879_posts.ID ORDER BY wp_15797879_posts.post_date DESC LIMIT 0, 10
The JOIN for mt1 is unset and the meta_value ignored (http://core.trac.wordpress.org/browser/trunk/wp-includes/meta.php?rev=23961#L789) resulting in an invalid query and an SQL error:
Unknown column 'mt1.meta_key' in 'where clause'
comment:7
johnjamesjacoby — 6 weeks ago
- Cc johnjamesjacoby added
In 1276/tests:

Reproduced in 3.4.