做数据采集和分析,MySQL 是迟早要碰的。但接单阶段用不到很深,基础会了就能开工。
核心 SQL 十条:
-- 查询
SELECT col1, col2 FROM table WHERE col1 = 'x' LIMIT 10;
-- 插入
INSERT INTO table (col1, col2) VALUES ('a', 'b');
-- 更新
UPDATE table SET col1 = 'y' WHERE id = 1;
-- 删除
DELETE FROM table WHERE id = 1;
-- 聚合
SELECT category, COUNT(*) FROM table GROUP BY category;
-- 排序
SELECT * FROM table ORDER BY created_at DESC;
-- 关联
SELECT a.*, b.name FROM comments a JOIN users b ON a.user_id = b.id;
-- 去重
SELECT DISTINCT user_id FROM comments;
-- 创建表
CREATE TABLE comments (
id INT PRIMARY KEY AUTO_INCREMENT,
content TEXT,
created_at DATETIME
);
-- 加索引
CREATE INDEX idx_user ON comments(user_id);
|
Python 操作:
import pymysql
conn = pymysql.connect(
host='localhost', user='root',
password='xxx', database='mydb'
)
cursor = conn.cursor()
cursor.execute("SELECT * FROM comments LIMIT 5")
print(cursor.fetchall())
|
进阶用法(SQLAlchemy 之类的 ORM)后面单独聊。
本文由 BBZ · 小朵科技工作室 出品。