0

我有一个问题,我需要在 MySQL 查询中作为列并在该列上执行 BETWEEN。我能想出的最简单的版本说明了这个问题:

SELECT ID AS post_id FROM wp_posts WHERE (post_id BETWEEN 10 AND 20)

这会引发以下错误:

#1054 - Unknown column 'post_id' in 'where clause'

有没有办法让新创建的post_id列对 BETWEEN 运算符可见?

更新:

这是我的实际查询。如您所见,它稍微复杂一些:

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
4

3 回答 3

3

标准 SQL 不允许在 WHERE 子句中引用列别名。

施加此限制是因为在评估 WHERE 子句时,可能尚未确定列值。(http://dev.mysql.com/doc/refman/5.0/en/problems-with-alias.html

于 2011-06-27T04:40:09.777 回答
3

MySQL 文档

不允许在 WHERE 子句中引用列别名,因为在执行 WHERE 子句时可能尚未确定列值。

您要么必须在子句中使用ID而不是使用子句。post_idWHEREHAVING

例如:

SELECT ID AS post_id FROM wp_posts WHERE ID BETWEEN 10 AND 20

更新:根据您最近的更新,您可以使用已经建议的子查询,或者像我之前建议的那样,您可以使用HAVING子句。

例如:

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     wp_posts.post_status = 'publish' AND
          wp_posts.post_type = 'store'
GROUP BY  wp_postmeta.post_id
HAVING    lng BETWEEN 150.29793837662 AND 152.1161201948 AND 
          lat BETWEEN -34.775666623377 AND -32.957484805195
于 2011-06-27T04:41:18.337 回答
2

是的你可以!

SELECT post_id
from (select id AS post_id FROM wp_posts) x
WHERE post_id BETWEEN 10 AND 20

编辑以包括对问题的更改。试试这个(没有在mysql中运行,但如果不正确应该关闭):

SELECT *
FROM (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
GROUP BY wp_postmeta.post_id
) x
LEFT JOIN wp_posts ON wp_posts.ID = x.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'
于 2011-06-27T04:44:45.007 回答