I have an issue where I need to AS a column in a MySQL query and execute a BETWEEN on that column. The simplest version I can come up with that illustrates the problem is this:
SELECT ID AS post_id FROM wp_posts WHERE (post_id BETWEEN 10 AND 20)
This throws the following error:
#1054 - Unknown column 'post_id' in 'where clause'
Is there a way to make the newly created post_id column visible to the BETWEEN operator?
UPDATE:
This is my actual query. As you can see, it is slightly more complicated:
SELECT wp_postmeta.post_id,
MAX(CASE WHEN wp_postmeta.meta_key='store_lng' THEN wp_postmeta.meta_value END ) AS lng,
MAX(CASE WHEN wp_postmeta.meta_key='store_lat' THEN wp_postmeta.meta_value END ) AS lat
FROM wp_postmeta
LEFT JOIN wp_posts ON (wp_posts.ID=wp_postmeta.post_id)
WHERE
(lng BETWEEN 150.29793837662 AND 152.1161201948)
AND
(lat BETWEEN -34.775666623377 AND -32.957484805195)
AND
wp_posts.post_status='publish'
AND
wp_posts.post_type='store'
GROUP BY wp_postmeta.post_id
From the MySQL documentation:
You’ll either have to use
IDinstead ofpost_idin theWHEREclause or use aHAVINGclause.For example:
Update: Based on your most recent update, you could use a subquery as already suggested or as I suggested earlier, you could use a
HAVINGclause.For example: