MySQL:WHERE 值大于 Min 且小于 Max
Posted
技术标签:
【中文标题】MySQL:WHERE 值大于 Min 且小于 Max【英文标题】:MySQL: WHERE value is greater than Min and less than Max 【发布时间】:2013-01-22 01:16:03 【问题描述】:这是我的查询:
SELECT wp_posts.ID, wp_posts.post_title, lat.meta_value AS latitude, lng.meta_value AS longitude, info1.meta_value AS street_no, info2.meta_value AS street, info3.meta_value AS street_suffix, price.meta_value AS price,
( 3959 * acos( cos( radians( '$latitude' ) ) * cos( radians( lat.meta_value ) ) * cos( radians( lng.meta_value ) - radians( '$longitude' ) ) + sin( radians( '$latitude' ) ) * sin( radians( lat.meta_value ) ) ) ) AS distance
FROM wp_posts
LEFT JOIN wp_postmeta AS lat
ON lat.post_id = wp_posts.ID
AND lat.meta_key = 'property_lat'
LEFT JOIN wp_postmeta AS lng
ON lng.post_id = wp_posts.ID
AND lng.meta_key = 'property_long'
LEFT JOIN wp_postmeta AS info1
ON info1.post_id = wp_posts.ID
AND info1.meta_key = 'street_no'
LEFT JOIN wp_postmeta AS info2
ON info2.post_id = wp_posts.ID
AND info2.meta_key = 'street'
LEFT JOIN wp_postmeta AS info3
ON info3.post_id = wp_posts.ID
AND info3.meta_key = 'street_suffix'
LEFT JOIN wp_postmeta AS price
ON price.post_id = wp_posts.ID
AND price.meta_key = 'price_current'
WHERE lat.meta_key IS NOT NULL
HAVING distance < 30
LIMIT 0, 20
我需要更新WHERE
声明以考虑price_min
和price_max
值...仅返回结果WHERE price is >= $price_min AND <= $price_max
我希望这是有道理的......
【问题讨论】:
你试过了吗?WHERE lat.meta_key IS NOT NULL AND price is >= $price_min AND <= $price_max
可惜你没有:) 相应地添加正确的表别名。
You have an error in your SQL syntax;
【参考方案1】:
假设您每个 id 只获得一行,我建议您将查询重写为聚合:
select p.*,
( 3959 * acos( cos( radians( '$latitude' ) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians( '$longitude' ) ) + sin( radians( '$latitude' ) ) * sin( radians( latitude ) ) ) ) AS distance
from (select p.id,
max(case when meta_key = 'property_lat' then meta_value end) as latitude,
max(case when meta_key = 'property_long' then meta_value end) as longitude,
max(case when meta_key = 'street_no' then meta_value end) as street_no,
max(case when meta_key = 'street' then meta_value end) as street,
max(case when meta_key = 'street_suffix' then meta_value end) as street_suffix,
max(case when meta_key = 'price_current' then meta_value end) as price_current
from wp_posts p
group by p.id
) p
WHERE latitude IS NOT NULL and distance < 30
LIMIT 0, 20
此查询未经测试,因此可能存在语法错误。
有了这个结构,你只需添加:
price_current is >= $price_min AND <= $price_max
到外部查询。我假设您的意思是 price_current,因为价格不在原始查询中。
【讨论】:
这种情况下的外部查询是什么? 这是一种定义新列并在where
子句中使用这些列的方法。这似乎就是您在原始查询中使用having
子句的原因——我觉得这很混乱,因为having
子句应该暗示group by
。
错误:near 'from wp_posts p group by p.id ) p WHERE latitude IS NOT NULL and di' at line 10
以上是关于MySQL:WHERE 值大于 Min 且小于 Max的主要内容,如果未能解决你的问题,请参考以下文章