sql查询多个表时出错

时间:2014-05-11 11:16:10

标签: sql

我必须查询多个表格(tcountry, tcity, tcompany, temployee)以获得国家/城市/人口/公司/所包含员工数量的最终答案。某处我一定是犯了错误。

tcountrytcity有一列具有相同的名称(country_name),表tcitytcompany也有一列具有相同的列名称(city_name),表格tcompanytemployee都有一列具有相同的名称(company_name)。

查询:

SELECT 
    tcountry.country_name AS country, 
    tcountry.country_population AS population1,
    tcity.city_name AS city, 
    tcity.city_population AS population2,
    tcompany.company_name AS company,
    COUNT AS (*) employee 
FROM 
    temployee 
INNER JOIN 
    tcity ON temployee.company_city_name = tcity.city 
INNER JOIN 
    tcountry ON tcity.country_name = tcountry.country
ORDER BY 
    number_of_employees

1 个答案:

答案 0 :(得分:1)

COUNT AS (*) employee

应该是

COUNT(*) AS  employee

此外,我相信你的意思是说COUNT(*) AS number_of_employees

正如marc_s已经指出的那样;即使您从该表中提取了一列,您也不会加入tcompany

您的查询应该是

SELECT 
    tcountry.country_name AS country, 
    tcountry.country_population AS population1,
    tcity.city_name AS city, 
    tcity.city_population AS population2,
    tcompany.company_name AS company,
    COUNT(*) AS number_of_employees <-- Here
FROM 
    temployee 
INNER JOIN 
    tcity ON temployee.company_city_name = tcity.city 
INNER JOIN 
    tcountry ON tcity.country_name = tcountry.country
INNER JOIN tcompany 
ON tcompany.company_name = temployee.company_name <-- assumption 
ORDER BY 
    number_of_employees
相关问题