SELECT * FROM table_name;
,2. 选择特定列:SELECT column1, column2 FROM table_name;
,3. 条件查询:SELECT * FROM table_name WHERE condition;
,4. 排序结果:SELECT * FROM table_name ORDER BY column ASC/DESC;
,5. 聚合函数:SELECT COUNT(*), AVG(column) FROM table_name;
,6. 分组查询:SELECT column, COUNT(*) FROM table_name GROUP BY column;
,7. 连接查询:SELECT a.column1, b.column2 FROM table1 a JOIN table2 b ON a.id = b.id;
,8. 子查询:SELECT * FROM table_name WHERE column IN (SELECT column FROM another_table);
一、基本查询
选择特定列:SELECT column1, column2 FROM table_name;
选择所有列:SELECT * FROM table_name;
选择不同的值:SELECT DISTINCT column1 FROM table_name;
二、条件查询
使用WHERE子句:SELECT * FROM table_name WHERE condition;
运算符使用:
等于 :=
不等于 :!=
或<>
大于 :>
小于 :<
大于等于 :>=
小于等于 :<=
BETWEEN :BETWEEN value1 AND value2
IN :IN (value1, value2, ...)
LIKE :LIKE 'pattern'
IS NULL :IS NULL
AND :AND
OR :OR
NOT :NOT
三、排序与限制
排序查询结果:SELECT * FROM table_name ORDER BY column1 [ASC|DESC];
限制查询结果数量:
使用LIMIT:LIMIT number
使用TOP(适用于部分数据库如SQL Server):TOP number
四、聚合函数与GROUP BY
聚合函数:
COUNT()
SUM()
AVG()
MAX()
MIN()
分组查询:SELECT column1, aggregate_function(column2) FROM table_name GROUP BY column1;
HAVING子句筛选分组结果:SELECT column1, aggregate_function(column2) FROM table_name GROUP BY column1 HAVING condition;
五、连接查询
INNER JOIN:SELECT columns FROM table1 INNER JOIN table2 ON table1.common_column = table2.common_column;
LEFT JOIN:SELECT columns FROM table1 LEFT JOIN table2 ON table1.common_column = table2.common_column;
RIGHT JOIN:SELECT columns FROM table1 RIGHT JOIN table2 ON table1.common_column = table2.common_column;
FULL OUTER JOIN(若支持):SELECT columns FROM table1 FULL OUTER JOIN table2 ON table1.common_column = table2.common_column;
CROSS JOIN:SELECT columns FROM table1 CROSS JOIN table2;
(无关联条件)
六、子查询
在SELECT语句中:SELECT * FROM table_name WHERE column_name = (SELECT column_name FROM another_table WHERE condition);
在FROM子句中:FROM (SUBQUERY) AS temporary_table
在EXISTS子句中:SELECT * FROM table_name WHERE EXISTS (SELECT 1 FROM another_table WHERE condition);
七、插入、更新与删除操作
插入数据:INSERT INTO table_name (column1, column2, ...) VALUES (value1, value2, ...);
更新数据:UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE condition;
删除数据:DELETE FROM table_name WHERE condition;
问题与解答
1、何时使用INNER JOIN与LEFT JOIN?
解答:INNER JOIN用于当你只想获取两个表中完全匹配的记录时,即只有当连接条件满足时,才会返回结果集中的行,而LEFT JOIN(或LEFT OUTER JOIN)则用于即使你只从左表(第一个被提及的表)中有不匹配的记录,你也想要它们出现在结果集中,对于右表(第二个被提及的表)中没有匹配的记录,相应位置会返回NULL,简而言之,如果你需要包含左表的所有记录,不论右表中是否有匹配项,就使用LEFT JOIN;如果只需要两边都有匹配的记录,则使用INNER JOIN。
2、如何在SQL中实现分页查询?
解答:分页查询常通过结合ORDER BY和LIMIT(或其等效子句,如SQL Server中的OFFSETFETCH)来实现,以MySQL为例,假设每页显示10条记录,要查询第二页的数据,可以使用以下SQL语句:SELECT * FROM table_name ORDER BY id ASC LIMIT 10 OFFSET 10;
这里,LIMIT 10
意味着返回10条记录,OFFSET 10
意味着跳过前10条记录,从而得到第11到第20条记录,实现了分页效果,在其他数据库系统中,如SQL Server,可以使用OFFSETFETCH
语法实现相同功能。
来源互联网整合,作者:小编,如若转载,请注明出处:https://www.aiboce.com/ask/108343.html