PostgreSQL - 选择查询

  • 简述

    PostgreSQLSELECT语句用于从数据库表中获取数据,以结果表的形式返回数据。这些结果表称为结果集。
  • 句法

    SELECT 语句的基本语法如下 -
    
    SELECT column1, column2, columnN FROM table_name;
    
    这里,column1,column2...是表的字段,您要获取其值。如果要获取字段中所有可用字段,则可以使用以下语法 -
    
    SELECT * FROM table_name;
    
  • 例子

    考虑具有以下记录的表 COMPANY -
    
    -- This is the file to create COMPANY table and to populate it with 7 records.
    -- Just copy and past them on psql prompt.
    DROP TABLE COMPANY;
    CREATE TABLE COMPANY(
       ID INT PRIMARY KEY     NOT NULL,
       NAME           TEXT    NOT NULL,
       AGE            INT     NOT NULL,
       ADDRESS        CHAR(50),
       SALARY         REAL
    );
    INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
    VALUES (1, 'Paul', 32, 'California', 20000.00 );
    
    INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
    VALUES (2, 'Allen', 25, 'Texas', 15000.00 );
    
    INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
    VALUES (3, 'Teddy', 23, 'Norway', 20000.00 );
    
    INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
    VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 );
    
    INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
    VALUES (5, 'David', 27, 'Texas', 85000.00 );
    
    INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
    VALUES (6, 'Kim', 22, 'South-Hall', 45000.00 );
    
    INSERT INTO COMPANY VALUES (7, 'James', 24, 'Houston', 10000.00 );
    
    
     id | name  | age | address   | salary
    ----+-------+-----+-----------+--------
      1 | Paul  |  32 | California|  20000
      2 | Allen |  25 | Texas     |  15000
      3 | Teddy |  23 | Norway    |  20000
      4 | Mark  |  25 | Rich-Mond |  65000
      5 | David |  27 | Texas     |  85000
      6 | Kim   |  22 | South-Hall|  45000
      7 | James |  24 | Houston   |  10000
    (7 rows)
    
    以下是一个示例,它将获取 CUSTOMERS 表中可用客户的 ID、Name 和 Salary 字段 -
    
    testdb=# SELECT ID, NAME, SALARY FROM COMPANY ;
    
    这将产生以下结果 -
    
      id | name  | salary
     ----+-------+--------
       1 | Paul  |  20000
       2 | Allen |  15000
       3 | Teddy |  20000
       4 | Mark  |  65000
       5 | David |  85000
       6 | Kim   |  45000
       7 | James |  10000
    (7 rows)
    
    如果要获取 CUSTOMERS 表的所有字段,请使用以下查询 -
    
    testdb=# SELECT * FROM COMPANY;
    
    这将产生以下结果 -
    
     id | name  | age | address   | salary
    ----+-------+-----+-----------+--------
      1 | Paul  |  32 | California|  20000
      2 | Allen |  25 | Texas     |  15000
      3 | Teddy |  23 | Norway    |  20000
      4 | Mark  |  25 | Rich-Mond |  65000
      5 | David |  27 | Texas     |  85000
      6 | Kim   |  22 | South-Hall|  45000
      7 | James |  24 | Houston   |  10000
    (7 rows)