这篇文章将为大家详细讲解有关MySQL表的基本查询操作大全(这一篇够了),小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
MySQL表的基本查询操作大全
查询表中的所有记录
SELECT * FROM table_name;
查询表中的特定列
SELECT column1, column2, ... FROM table_name;
查询表中的唯一记录
SELECT DISTINCT column_name FROM table_name;
按指定顺序查询记录
- 升序:
SELECT * FROM table_name ORDER BY column_name ASC;
- 降序:
SELECT * FROM table_name ORDER BY column_name DESC;
限制查询结果
- LIMIT子句:
SELECT * FROM table_name LIMIT number;
- OFFSET子句(与LIMIT子句配合使用):
SELECT * FROM table_name LIMIT number OFFSET offset;
在查询中使用WHERE子句
- 基本比较:
SELECT * FROM table_name WHERE column_name = value;
- 多条件比较:
SELECT * FROM table_name WHERE column_name1 = value1 AND column_name2 = value2;
- 范围查询:
SELECT * FROM table_name WHERE column_name BETWEEN start_value AND end_value;
- 模式匹配:
SELECT * FROM table_name WHERE column_name LIKE "pattern%";
使用聚合函数
- COUNT:
SELECT COUNT(*) FROM table_name;
- SUM:
SELECT SUM(column_name) FROM table_name;
- AVG:
SELECT AVG(column_name) FROM table_name;
- MIN:
SELECT MIN(column_name) FROM table_name;
- MAX:
SELECT MAX(column_name) FROM table_name;
使用GROUP BY子句
SELECT column_name, COUNT(*) FROM table_name GROUP BY column_name;
使用HAVING子句
SELECT column_name, COUNT(*) FROM table_name GROUP BY column_name HAVING COUNT(*) > 1;
使用子查询
- 嵌套子查询:
SELECT * FROM table_name WHERE column_name IN (SELECT column_name FROM another_table_name);
- 关联子查询:
SELECT t1.column_name FROM table1 AS t1, table2 AS t2 WHERE t1.column_name = t2.column_name;
使用JOIN
- INNER JOIN:
SELECT * FROM table1 INNER JOIN table2 ON table1.column_name = table2.column_name;
- LEFT JOIN:
SELECT * FROM table1 LEFT JOIN table2 ON table1.column_name = table2.column_name;
- RIGHT JOIN:
SELECT * FROM table1 RIGHT JOIN table2 ON table1.column_name = table2.column_name;
- FULL JOIN:
SELECT * FROM table1 FULL JOIN table2 ON table1.column_name = table2.column_name;
其他有用的查询技巧
- 使用UNION操作符合并查询结果:
SELECT * FROM table1 UNION SELECT * FROM table2;
- 使用NOT IN运算符查找不在指定值集合中的记录:
SELECT * FROM table_name WHERE column_name NOT IN (value1, value2, ...);
- 使用EXISTS运算符检查子查询中是否存在记录:
SELECT * FROM table_name WHERE EXISTS (SELECT * FROM another_table_name WHERE column_name = "value");
以上就是MySQL表的基本查询操作大全(这一篇够了)的详细内容,更多请关注编程学习网其它相关文章!