sql查询多个表时出错
我必须查询多个表(sql查询多个表时出错,sql,Sql,我必须查询多个表(tcountry、tcity、tcompany、temployee),以获得包含国家/城市/人口/公司/员工人数的最终答案。我一定是在什么地方出错了 表tccountry和tcity有一列同名(country\u name),表tcity和tcompany也有一列同名(city\u name),表tcompany和temployee都有一列同名(公司名称) 查询: SELECT tcountry.country_name AS country, tcount
tcountry、tcity、tcompany、temployee
),以获得包含国家/城市/人口/公司/员工人数的最终答案。我一定是在什么地方出错了
表tccountry
和tcity
有一列同名(country\u name
),表tcity
和tcompany
也有一列同名(city\u name
),表tcompany
和temployee
都有一列同名(公司名称
)
查询:
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
应该是
COUNT(*) AS employee
此外,我相信你的意思是说,COUNT(*)作为员工人数
正如marc_s已经指出的那样,您并没有加入t公司
,即使您正在从该表中提取一列
您的查询应该如下所示
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
选择
t country.country\u名称为国家,
t国家/国家/人口1,
tcity.city\u名称为城市,
tcity.city_人口作为人口2,
t company.company\u公司名称,
计数(*)作为员工数量,您在SELECT
命令的列列表中列出了tcompany
中的一列,但是表tcompany
没有显示在任何JOIN
语句中……您还没有列出您的RDBMS-大多数都会抛出语法错误,因为您没有groupby
似乎不需要任何东西,只需要员工计数,您可以在表引用子查询中按公司名称
进行分组,该子查询应该能够在该列上使用索引(与当前查询相反,在当前查询中,生成的分组依据
太宽,无法进行此操作)。请注意,对于有时会发生变化的信息(如公司名称),通常最好引入一个代理密钥
,通常是一个数字,以供参考/加入。感谢大家的评论。出于某种原因,我现在得到的答案是,员工人数比实际人数多2倍(Y市X公司有5名员工,但我有10名员工,以此类推).有什么想法吗?@user3625305,如果没有看到样本数据,就无法回答这个问题。很可能是两个国家/城市都重复了。此外,这是一个单独的问题,应该单独发布。我建议您关闭此线程,发布一个单独的问题,其中包含所有表架构以及中所有表中的少量样本数据也别忘了接受这个答案。
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