Sql基础语句及一些sql复杂查询语句
以下是一些常见的SQL基础语句和复杂查询的例子:
基础语句
-- 创建表
CREATE TABLE users (
id INT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
email VARCHAR(100) NOT NULL UNIQUE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- 插入数据
INSERT INTO users (id, username, email) VALUES (1, 'user1', 'user1@example.com');
-- 查询数据
SELECT * FROM users;
-- 更新数据
UPDATE users SET username = 'newuser' WHERE id = 1;
-- 删除数据
DELETE FROM users WHERE id = 1;
-- 删除表
DROP TABLE users;
复杂查询
-- 内连接查询
SELECT u.username, o.order_date
FROM users u
INNER JOIN orders o ON u.id = o.user_id;
-- 左外连接查询
SELECT u.username, o.order_date
FROM users u
LEFT JOIN orders o ON u.id = o.user_id;
-- 右外连接查询
SELECT u.username, o.order_date
FROM users u
RIGHT JOIN orders o ON u.id = o.user_id;
-- 子查询
SELECT username
FROM users
WHERE id IN (SELECT user_id FROM orders WHERE order_date = '2023-01-01');
-- 分组和聚合
SELECT gender, COUNT(*)
FROM users
GROUP BY gender;
-- 分页查询
SELECT *
FROM users
ORDER BY id
LIMIT 10 OFFSET 20; -- 跳过20条数据,获取接下来的10条数据
-- 创建索引
CREATE INDEX idx_email ON users(email);
-- 使用索引
SELECT * FROM users FORCE INDEX (idx_email) WHERE email = 'user1@example.com';
-- 使用视图
CREATE VIEW active_users AS
SELECT id, username
FROM users
WHERE created_at > '2023-01-01';
-- 查询视图
SELECT * FROM active_users;
这些例子涵盖了基础的SQL操作和一些复杂查询技巧,如连接查询、子查询、分组和聚合、分页、索引和视图。这些操作是数据库操作的基础,对于学习和使用SQL数据库至关重要。
评论已关闭