【问题标题】:Writing query for multiple tables in php在php中编写多个表的查询
【发布时间】:2014-11-12 20:53:44
【问题描述】:

我正在为我的作业写最后一个查询,但我现在卡在它上面。此查询要求我从 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                  | 

【问题讨论】:

  • This 可能会给你一个线索。
  • 请不要在问题得到解答后删除重要/相关信息。这只会让其他来这里学习相同事物的人感到困惑。 (我已经撤消了您的更改)。您可能想阅读堆栈溢出的欢迎指南/导览:stackoverflow.com/tour

标签: php postgresql


【解决方案1】:

正如上面评论中提到的,在这种情况下,您必须执行 SQL(内部)联接。所以你会有类似的东西:

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

【讨论】:

  • 我还有一个问题要问你。我是否必须使用关键字 DISTINCT 才能在表中查找语言英语?还是我只做 WHERE (language = "English") AND (is_official IS TRUE)
  • 不,您不必使用 DISTINCT,它用于过滤 sql-tutorial.com/sql-distinct-sql-tutorial 如果您的问题得到解决,请不要忘记接受答案。
【解决方案2】:

一个好的起点是the PostgreSQL tutorial,尤其是joins between tables

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-25
    • 1970-01-01
    • 2021-12-04
    • 2019-06-10
    • 2017-02-18
    • 1970-01-01
    相关资源
    最近更新 更多