1、SELECT: 用于从数据库表中检索数据。
“`sql
SELECT column1, column2, … FROM table_name;
“`
要从名为 "employees" 的表中选择所有员工的姓名和工资:
“`sql
SELECT name, salary FROM employees;
“`
2、WHERE: 用于过滤结果集,只返回满足指定条件的记录。
“`sql
SELECT column1, column2, … FROM table_name WHERE condition;
“`
要选择年龄大于30岁的员工的名字和工资:
“`sql
SELECT name, salary FROM employees WHERE age > 30;
“`
3、ORDER BY: 用于对结果集进行排序。
“`sql
SELECT column1, column2, … FROM table_name ORDER BY column_name ASC|DESC;
“`
按工资降序排列员工:
“`sql
SELECT name, salary FROM employees ORDER BY salary DESC;
“`
4、GROUP BY: 用于将结果集按照一个或多个列进行分组。
“`sql
SELECT column1, aggregate_function(column2) FROM table_name GROUP BY column1;
“`
计算每个部门的平均薪水:
“`sql
SELECT department, AVG(salary) FROM employees GROUP BY department;
“`
5、HAVING: 用于过滤聚合函数的结果。
“`sql
SELECT column1, aggregate_function(column2) FROM table_name GROUP BY column1 HAVING condition;
“`
找出平均薪水超过50000的部门:
“`sql
SELECT department, AVG(salary) FROM employees GROUP BY department HAVING AVG(salary) > 50000;
“`
6、JOIN: 用于结合两个或多个表的行。
“`sql
SELECT column1, column2, … FROM table1 JOIN table2 ON table1.column = table2.column;
“`
列出所有员工及其所属部门的名称:
“`sql
SELECT employees.name, departments.department_name FROM employees JOIN departments ON employees.department_id = departments.department_id;
“`
7、INSERT INTO: 用于向表中插入新记录。
“`sql
INSERT INTO table_name (column1, column2, …) VALUES (value1, value2, …);
“`
添加一个新员工:
“`sql
INSERT INTO employees (name, salary, age) VALUES (‘John Doe’, 60000, 35);
“`
8、UPDATE: 用于修改表中的现有记录。
“`sql
UPDATE table_name SET column1 = value1, column2 = value2, … WHERE condition;
“`
将所有年龄大于40的员工的工资增加10%:
“`sql
UPDATE employees SET salary = salary * 1.1 WHERE age > 40;
“`
9、DELETE: 用于从表中删除记录。
“`sql
DELETE FROM table_name WHERE condition;
“`
删除所有年龄小于25岁的员工:
“`sql
DELETE FROM employees WHERE age < 25;
“`
10、LIMIT: 用于限制返回的记录数。
“`sql
SELECT column1, column2, … FROM table_name LIMIT number;
“`
仅显示前5名薪水最高的员工:
“`sql
SELECT name, salary FROM employees ORDER BY salary DESC LIMIT 5;
“`
相关问题与解答:
1、问题: 如何在 SQL 中使用子查询?
解答: 在 SQL 中,可以在另一个 SQL 查询内部使用子查询,子查询可以出现在各种 SQL 语句中,如 SELECT、FROM、WHERE 和 HAVING 子句,子查询必须始终用括号括起来,并且通常放在比较运算符(如 =、<>、>、<、>=、<=)之后,要找到工资高于平均工资的员工,可以使用以下子查询:
“`sql
SELECT name, salary FROM employees WHERE salary > (SELECT AVG(salary) FROM employees);
“`
来源互联网整合,作者:小编,如若转载,请注明出处:https://www.aiboce.com/ask/18716.html