在php中编写多个表的查询

时间:2014-09-18 13:24:39

标签: php postgresql

我正在写我的作业的最后一个问题,但我现在仍然坚持下去。这个查询要求我从2个表而不是1个表中获取信息。我对如何从两个表中获取这些信息以及如何将它们放在一起感到困惑。以下是我要编写的查询的说明。

Find the name, independence year, and region of all countries where English is an official language.
Order results by region ascending and alphabetize the results within each region by country name.   
(44 results)

以下是我将用于此查询的表格

Table "lab2.country_language"
Column    |         Type          |               Modifiers                
--------------+-----------------------+----------------------------------------
 country_code | character(3)          | not null default ''::bpchar
 language     | character varying(30) | not null default ''::character varying
 is_official  | boolean               | not null default false
 percentage   | real                  | not null default 0::real
Indexes:
 "country_language_pkey" PRIMARY KEY, btree (country_code, language)
Foreign-key constraints:
"country_language_country_code_fkey" FOREIGN KEY (country_code) REFERENCES country(country_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                  | 

2 个答案:

答案 0 :(得分:2)

如上面的评论所述,在这种情况下你必须进行SQL(内部)连接。所以你会有类似的东西:

SELECT name, indep_year, region 
FROM lab2.country 
JOIN lab2.country_language
ON lab2.country.country_code = lab2.country_language.country_code
WHERE …

答案 1 :(得分:0)

一个好的起点是the PostgreSQL tutorial,特别是joins between tables

您必须在两个表之间执行内部联接,以将它们链接到一个更大的虚拟行,然后您可以过滤并从中选择单个列。

本教程提供了比我更好的示例。

相关问题