postgresql中的嵌套子查询

时间:2013-10-25 12:44:41

标签: postgresql

我有这三个表

CREATE TABLE "Countries"
(
  name text NOT NULL,
  pop integer,
  CONSTRAINT country PRIMARY KEY (name),
  CONSTRAINT pop_check CHECK (pop > 0)
)

CREATE TABLE "Cities"
( name text NOT NULL, pop integer,
  country_name text,
  CONSTRAINT "City_ref" PRIMARY KEY (name),
  CONSTRAINT country_ref FOREIGN KEY (country_name)
      REFERENCES "db1001002_Countries" (name) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT "Population" CHECK (pop > 0)
);

CREATE TABLE " Company"
(
  "City_name" text NOT NULL,
  "Company_Name" text NOT NULL,
  no_of_employee integer,
  CONSTRAINT "City_company" PRIMARY KEY ("City_name", "Company_Name"),
  CONSTRAINT city_ref FOREIGN KEY ("City_name")
      REFERENCES "Cities" (name) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT employee_check CHECK (no_of_employee > 0)
)

我的问题是我想以格式

使用嵌套查询
select field(s) from table(s)
where field(s) in (select field(s) from table(s) condition)
group by field(s) 

获取包含字段的新表

country, min_pop, max_pop, average_pop 
for cities with pop > 500000

我尝试编写一些查询,但是我在子查询中不断收到太多字段的错误。 我正在使用postgresql 9.3。

当我使用此查询时,我得到了一些结果。

SELECT country_name, min_pop, max_pop, avg_popo
  FROM (SELECT country_name, min(pop),max(pop),avg(pop)
  FROM
  "Cities"
  GROUP BY country_name)
  AS popcal(country_name,min_pop, max_pop, avg_popo)
  WHERE min_pop>500000

是否无法以此格式编写查询

select field(s) from table(s)
where field(s) in (select field(s) from table(s) condition)
group by field(s) 

2 个答案:

答案 0 :(得分:1)

我不确定我是否理解这个问题,但是如果您想要首先过滤至少一个人口超过50,000的城市,则可以这样使用子查询:

SELECT country_name, MIN(pop) AS min_pop, MAX(pop) AS max_pop, avg(pop) AS avg_pop
FROM "Cities"
  WHERE country_name IN (
    SELECT DISTINCT country_name
    FROM
      "Cities"
    WHERE pop>500000)
GROUP BY country_name

子查询返回您需要的国家/地区,然后您可以将其用于汇总查询。

答案 1 :(得分:0)

请编辑原始问题。鉴于你的评论,你问的是一个完全不同的问题...... AndreaBoc's answer是正确的。