Programming·

SQL Cheat Sheet

SQL相关的速查表,涵盖了一些常见的SQL操作.

基础查询

  • 选择所有列SELECT * FROM table_name;
  • 选择特定列SELECT column1, column2 FROM table_name;
  • 去重记录SELECT DISTINCT column1 FROM table_name;

条件查询

  • 基本条件SELECT * FROM table_name WHERE condition;
  • 逻辑运算符AND, OR, NOT
    • SELECT * FROM table_name WHERE condition1 AND condition2;
  • 范围查询BETWEEN, IN
    • SELECT * FROM table_name WHERE column1 BETWEEN value1 AND value2;
    • SELECT * FROM table_name WHERE column1 IN (value1, value2, value3);
  • 模式匹配LIKE
    • SELECT * FROM table_name WHERE column1 LIKE 'pattern';

聚合函数

  • 计数COUNT()
    • SELECT COUNT(column1) FROM table_name;
  • 求和SUM()
    • SELECT SUM(column1) FROM table_name;
  • 平均值AVG()
    • SELECT AVG(column1) FROM table_name;
  • 最大值MAX()
    • SELECT MAX(column1) FROM table_name;
  • 最小值MIN()
    • SELECT MIN(column1) FROM table_name;

分组与排序

  • 分组GROUP BY
    • SELECT column1, COUNT(*) FROM table_name GROUP BY column1;
  • 过滤分组HAVING
    • SELECT column1, COUNT(*) FROM table_name GROUP BY column1 HAVING COUNT(*) > 1;
  • 排序ORDER BY
    • SELECT * FROM table_name ORDER BY column1 ASC;
    • SELECT * FROM table_name ORDER BY column1 DESC;

联接(JOIN)

  • 内联接INNER JOIN
    • SELECT * FROM table1 INNER JOIN table2 ON table1.column = table2.column;
  • 左联接LEFT JOIN
    • SELECT * FROM table1 LEFT JOIN table2 ON table1.column = table2.column;
  • 右联接RIGHT JOIN
    • SELECT * FROM table1 RIGHT JOIN table2 ON table1.column = table2.column;
  • 全联接FULL OUTER JOIN
    • SELECT * FROM table1 FULL OUTER JOIN table2 ON table1.column = table2.column;

子查询

  • 嵌套查询SELECT * FROM table_name WHERE column1 = (SELECT column1 FROM table_name2 WHERE condition);

数据操作

  • 插入数据INSERT INTO
    • INSERT INTO table_name (column1, column2) VALUES (value1, value2);
  • 更新数据UPDATE
    • UPDATE table_name SET column1 = value1 WHERE condition;
  • 删除数据DELETE
    • DELETE FROM table_name WHERE condition;

创建和修改表

  • 创建表CREATE TABLE
    • CREATE TABLE table_name (column1 datatype, column2 datatype, ...);
  • 修改表ALTER TABLE
    • ALTER TABLE table_name ADD column_name datatype;
    • ALTER TABLE table_name DROP COLUMN column_name;
  • 删除表DROP TABLE
    • DROP TABLE table_name;