常用SQL命令大全
SQL(Structured Query Language)是一种用于管理关系数据库管理系统的标准编程语言。它用于执行各种操作,如查询、更新、插入和删除数据库中的数据。以下是一些常用的SQL命令:
- SELECT - 查询数据
SELECT column1, column2, ...
FROM table_name
WHERE condition;
示例:
SELECT name, age
FROM students
WHERE age > 20;
- INSERT - 插入数据
INSERT INTO table_name (column1, column2, ...)
VALUES (value1, value2, ...);
示例:
INSERT INTO students (name, age)
VALUES ('Alice', 25);
- UPDATE - 更新数据
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
示例:
UPDATE students
SET age = 26
WHERE name = 'Alice';
- DELETE - 删除数据
DELETE FROM table_name
WHERE condition;
示例:
DELETE FROM students
WHERE age < 18;
- CREATE TABLE - 创建新表
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
...
);
示例:
CREATE TABLE students (
id INT PRIMARY KEY,
name VARCHAR(50),
age INT
);
- ALTER TABLE - 修改表结构
ALTER TABLE table_name
ADD column_name datatype;
示例:
ALTER TABLE students
ADD email VARCHAR(100);
- DROP TABLE - 删除表
DROP TABLE table_name;
示例:
DROP TABLE students;
- JOIN - 表连接
SELECT column_name(s)
FROM table1
JOIN table2
ON table1.column_name = table2.column_name;
示例:
SELECT students.name, courses.course_name
FROM students
JOIN courses
ON students.course_id = courses.id;
- ORDER BY - 排序
SELECT column_name(s)
FROM table_name
ORDER BY column_name ASC|DESC;
示例:
SELECT name, age
FROM students
ORDER BY age DESC;
- GROUP BY - 分组
SELECT column_name(s), AGGREGATE_FUNCTION(column_name)
FROM table_name
WHERE condition
GROUP BY column_name;
示例:
SELECT age, COUNT(name) as total_students
FROM students
GROUP BY age;
- HAVING - 分组后的条件过滤
SELECT column_name(s), AGGREGATE_FUNCTION(column_name)
FROM table_name
WHERE condition
GROUP BY column_name
HAVING condition;
示例:
SELECT age, COUNT(name) as total_students
FROM students
GROUP BY age
HAVING COUNT(name) > 10;
- UNION - 合并查询结果
SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;
示例:
SELECT name FROM students
UNION
SELECT name FROM teachers;
这些是SQL中的一些基本命令,每个命令都有其特定的用途和语法。通过组合这些命令,你可以进行复杂的数据库操作。
正文到此结束
相关文章
热门推荐
评论插件初始化中...