我的目标是在排名前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
但我得到一个错误
子查询的列太多
1条答案
按热度按时间cotxawn71#
例如,在PostgreSQL中可以使用
with
查询,请参见Documentation: