【发布时间】:2014-09-19 04:21:41
【问题描述】:
我正在为我的作业写最后一个查询,但我现在卡在它上面。此查询要求我从 2 个表而不是 1 个表中获取信息。我对如何从两个表中获取这些信息以及如何将它们放在一起感到困惑。这是我正在尝试编写的查询的描述。
For each country display the capital city name and the percentage of the population that lives in
the capital for each country. Sort the results from largest percentage to smallest percentage.
对于这个查询,我相信我必须得到整个国家的人口,然后得到首都的人口,然后将它们除以得到居住在首都的人口百分比。我只是想不通我将如何执行这个数学运算,尤其是当数据来自 2 个不同的表时。我在这里先向您的帮助表示感谢。这是我将用于此查询的表
Table "lab2.city"
Column | Type | Modifiers
--------------+-----------------------+-----------------------------------------
id | integer | not null default nextval('city_id_seq'::regclass)
name | character varying(35) | not null default ''::character varying
country_code | character(3) | not null default ''::bpchar
district | character varying(20) | not null default ''::character varying
population | integer | not null default 0
Indexes:
"city_pkey" PRIMARY KEY, btree (id)
Foreign-key constraints:
"city_country_code_fkey" FOREIGN KEY (country_code) REFERENCES country(counry_code) ON DELETE CASCADE
=> \d country
Table "lab2.country"
Column | Type | Modifiers
-----------------+-----------------------+--------------------------------------
country_code | character(3) | not null default ''::bpchar
name | character varying(52) | not null default ''::character varying
continent | continent | not null
region | character varying(26) | not null default ''::character varying
surface_area | real | not null default 0::real
indep_year | smallint |
population | integer | not null default 0
life_expectancy | real |
gnp | real |
gnp_old | real |
local_name | character varying(45) | not null default ''::character varying
government_form | character varying(45) | not null default ''::character varying
head_of_state | character varying(60) | default NULL::character varying
capital | integer |
【问题讨论】:
-
INNER JOIN 是你的朋友。
-
不会给你完整的答案,但你想像之前的评论状态那样使用内连接。您的评估是正确的,您需要将城市人口除以国家人口,然后乘以 100。当您连接两个表时,您可以设置别名,这是数学方程式: SELECT * FROM lab2.city c JOIN lab2.country c2 ON c.country_code = c2.country_code 现在,如果你说 c2.population 它将是国家人口。如果您使用 c.population,它将使用城市人口值。
-
@espradley 这看起来正确吗? SELECT name FROM lab2.city c JOIN lab2.country c2 ON c.country_code = c2.country_code 我不明白我需要继续尝试哈哈
-
你已经问过了。有什么不同?如果您想发布后续内容,请展示您已经尝试过的内容以及遇到问题的地方。这个网站不是“为我做作业”……具体一点,展示你已经做过的事情。在这种情况下,我希望根据您的最后一个问题看到一个使用正确的
inner join的查询,以及一个关于如何使用生成的连接表的问题。另外,根据我在上一个问题中的建议,您是否按照教程进行? -
@user3596818 (回复已删除答案的评论):对我来说看起来一样,只是你扩展了这个。这甚至是前一个的第一部分的复制和粘贴。答案保持不变:使用内部连接。按照教程。如果您在完成本教程后仍然卡住,您可以发布一个更具体的问题,其中包含您尝试过的查询以及遇到的错误/卡住的点。
标签: php postgresql