返回多行的Mysql子查询

时间:2013-01-29 17:34:21

标签: mysql subquery

我正在尝试获取某个纬度和经度范围内的邮政编码,然后使用返回的邮政编码拉取给定区域内的所有帖子。纬度和经度的数字是变量,但出于测试目的,它们是硬数字。 有人能指导我朝着正确的方向努力吗?

查询#1 - 作品选择帖子

SELECT user_id, session, zip, price, city, state, post_id, category, shortDesc,  fpi 
FROM post ORDER BY post.post_id DESC;

查询#2 - 作品选择区域中的邮政编码

SELECT count(value) as duplicate, value 
from (SELECT DISTINCT zipcode as value from zip 
  WHERE latitude BETWEEN 27.747 AND 28.147 
  UNION all 
   SELECT DISTINCT zipcode FROM zip 
   WHERE longitude BETWEEN -82.657 AND -82.257) 
as tbl group by value having count(value) > 1;

查询为子查询

尝试:失败

SELECT user_id, session, zip, price, city, state, post_id, category, shortDesc,  fpi 
FROM post 
WHERE zip = (
  SELECT count(value) as duplicate ,value 
  from (SELECT DISTINCT zipcode as value from zip 
    WHERE latitude BETWEEN 27.747 AND 28.147 
    UNION all SELECT DISTINCT zipcode FROM zip 
     WHERE longitude BETWEEN -82.657 AND -82.257) 
  as tbl group by value having count(value) > 1) 
ORDER BY post.post_id DESC;

错误#1241 - 操作数应包含1列

下一步尝试:失败

SELECT user_id, session, zip, price, city, state, post_id, category, shortDesc,  fpi 
FROM post WHERE zip = (select distinct zipcode from zip 
  where latitude between 27.747 AND 28.147) 
  IN ( select distinct zipcode from zip 
    where longitude between -82.657 AND -82.257);

1242 - 子查询返回超过1行

下一步尝试:失败

SELECT user_id, session, zip, price, city, state, post_id, category, shortDesc,  fpi 
FROM post 
WHERE zip = ANY (
  select distinct zipcode from zip 
  where latitude between 27.747 AND 28.147) 
IN ( select distinct zipcode from zip 
     where longitude between -82.657 AND -82.257);

1064 - 您的SQL语法出错;

2 个答案:

答案 0 :(得分:0)

这应该有效。:

SELECT user_id, session, zip, price, city, 
  state, post_id, category, shortDesc, fpi 
FROM post WHERE zip in (SELECT DISTINCT zipcode as value 
                                      from zip 
                                    WHERE latitude BETWEEN 27.747 AND 28.147 
                                    and longitude BETWEEN -82.657 AND -82.257)
   ORDER BY post.post_id DESC;

答案 1 :(得分:0)

我不确定你想要什么

试试这个

select user_id, session, zip, price, city, state, post_id, category, shortDesc,  fpi 
FROM post WHERE zip in
(SELECT DISTINCT zipcode from zip where 
(latitude BETWEEN 27.747 AND 28.147) AND (longitude BETWEEN -82.657 AND -82.257))