简单查询指从 OceanBase 一个或多个表或视图中检索一个或多个列数据的操作,列的数量以及它们的数据类型和长度由表结构确定。而选择列表指的是 SELECT 关键字之后和 FROM 子句之前的表达式列表。

语法

  1. SELECT 列名1,列名2,列名3,… FROM 表;

表名、字段名和关键字 SELECTFROM 不区分大小写。查询的最后可以跟上分号(;),多条 SQL 可以同时执行。您可以使用 SELECT 语句中的 Hint 将指令或提示传递给 OceanBase 数据库优化器。优化器使用 Hint 为语句选择执行计划。

示例

创建一张员工表 employee,并向列 employee_idfirst_namelast_namemanager_idsalary 插入数据:

  1. CREATE TABLE employee (
  2. employee_id INT,
  3. first_name VARCHAR(50),
  4. last_name VARCHAR(50),
  5. manager_id INT,
  6. salary NUMERIC
  7. );
  8. INSERT INTO employee VALUES(111, 'DEL', 'FA BEN', 1, 1500);
  9. INSERT INTO employee VALUES(112, 'AXEL', 'BELL', 1, 1000);
  10. INSERT INTO employee VALUES(113, 'CRIS', 'RACHAR', 1, 1000);

简单查询示例

  • 查询部分列:
  1. SELECT first_name, last_name, salary FROM employee;
  2. +------------+-----------+--------+
  3. | FIRST_NAME | LAST_NAME | SALARY |
  4. +------------+-----------+--------+
  5. | DEL | FA BEN | 1500 |
  6. | AXEL | BELL | 1000 |
  7. | CRIS | RACHAR | 1000 |
  8. +------------+-----------+--------+
  • 查询所有列:
  1. SELECT * FROM employee;
  2. +-------------+------------+-----------+------------+--------+
  3. | EMPLOYEE_ID | FIRST_NAME | LAST_NAME | MANAGER_ID | SALARY |
  4. +-------------+------------+-----------+------------+--------+
  5. | 111 | DEL | FA BEN | 1 | 1500 |
  6. | 112 | AXEL | BELL | 1 | 1000 |
  7. | 113 | CRIS | RACHAR | 1 | 1000 |
  8. +-------------+------------+-----------+------------+--------+
  • 对列进行数学运算:
  1. SELECT salary+100 FROM employee;
  2. +------------+
  3. | SALARY+100 |
  4. +------------+
  5. | 1600 |
  6. | 1100 |
  7. | 1100 |
  8. +------------+
  • 给列取别名:
  1. SELECT salary*12 年薪 FROM employee;
  2. +--------+
  3. | 年薪 |
  4. +--------+
  5. | 18000 |
  6. | 12000 |
  7. | 12000 |
  8. +--------+
  • 字符串拼接:
  1. SELECT first_name || '-' || last_name AS 姓名 FROM employee;
  2. +-------------+
  3. | 姓名 |
  4. +-------------+
  5. | DEL-FA BEN |
  6. | AXEL-BELL |
  7. | CRIS-RACHAR |
  8. +-------------+
  • 数据去重:
  1. SELECT DISTINCT MANAGER_ID FROM employee;
  2. +------------+
  3. | MANAGER_ID |
  4. +------------+
  5. | 1 |
  6. +------------+
  • CASE WHEN 语句:
  1. SELECT salary, CASE WHEN salary >= 1000 then '高薪' WHEN salary >= 800 THEN '一般'
  2. ELSE '继续努力' END AS typeFROM employee;
  3. +--------+--------+
  4. | SALARY | TYPE |
  5. +--------+--------+
  6. | 1500 | 高薪 |
  7. | 1000 | 高薪 |
  8. | 1000 | 高薪 |
  9. +--------+--------+