postgresql 用SQL写一个子查询,如何合并两个查询?

5f0d552i  于 2023-01-05  发布在  PostgreSQL
关注(0)|答案(1)|浏览(195)

我的目标是在排名前10的城市中找到排名前10的国家。我成功地使用了以下查询:

SELECT 
    COUNT(A.customer_id) AS number_of_customers,
    D.country, C.city
FROM
    customer A
INNER JOIN 
    address B ON A.address_id = B.address_id
INNER JOIN 
    city C ON B.city_id = C.city_id
INNER JOIN 
    country D ON C.country_ID = D.country_ID
WHERE 
    country IN ('India', 'China', 'United States', 'Japan', 'Mexico', 'Brazil', 'Russian Federation', 'Phillipines', 'Turkey', 'Indonesia')
GROUP BY 
    C.city, D.country
ORDER BY 
    number_of_customers DESC
LIMIT 10

但我想使用子查询,而不是列出我使用前面的查询找到的国家:

SELECT 
    COUNT(A.customer_id) AS number_of_customers,
    D.country
FROM
    customer A
INNER JOIN 
    address B ON A.address_id = B.address_id
INNER JOIN 
    city C ON B.city_id = C.city_id
INNER JOIN 
    country D ON C.country_ID = D.country_ID
GROUP BY 
    D.country
ORDER BY 
    number_of_customers DESC
LIMIT 10

我怎样才能正确地组合这两个查询?当我尝试用我发布的第二个查询中的国家列表替换时,我一直得到不同的错误。如果这是一个愚蠢的问题,我道歉;我是个初学者。
我的尝试:

SELECT 
    COUNT(A.customer_id) AS number_of_customers,
    D.country, C.city
FROM
    customer A
INNER JOIN 
    address B ON A.address_id = B.address_id
INNER JOIN 
    city C ON B.city_id = C.city_id
INNER JOIN 
    country D ON C.country_ID = D.country_ID
WHERE 
    country IN (SELECT COUNT(A.customer_id) AS number_of_customers, D.country
                FROM customer A
                INNER JOIN address B ON A.address_id = B.address_id
                INNER JOIN city C ON B.city_id = C.city_id
                INNER JOIN country D ON C.country_ID = D.country_ID
                GROUP BY D.country
                ORDER BY number_of_customers DESC
                LIMIT 10)
GROUP BY 
    C.city, D.country
ORDER BY 
    number_of_customers DESC
LIMIT 10

但我得到一个错误
子查询的列太多

cotxawn7

cotxawn71#

例如,在PostgreSQL中可以使用with查询,请参见Documentation

WITH top_countries AS (
  SELECT count(A.customer_id) AS number_of_customers,
       D.country AS country
  FROM customer A
  INNER JOIN address B ON A.address_id = B.address_id
  INNER JOIN city C ON B.city_id = C.city_id
  INNER JOIN country D ON C.country_ID = D.country_ID
  GROUP BY D.country
  ORDER BY number_of_customers DESC
  LIMIT 10
)
SELECT count(A.customer_id) AS number_of_customers,
       D.country, C.city
FROM customer A
INNER JOIN address B ON A.address_id = B.address_id
INNER JOIN city C ON B.city_id = C.city_id
INNER JOIN country D ON C.country_ID = D.country_ID
WHERE country IN (SELECT tc.country FROM top_countries)
GROUP BY C.city,D.country
ORDER BY number_of_customers DESC
LIMIT 10

相关问题