查询所有字段 SELECT * FROM tb_name;
查询指定字段 SELECT id,name FROM tb_name;
查询单个字段 SELECT id FROM tb_name;
查询多个字段 SELECT id,name FROM tb_name;
查询指定记录
SELECT * FROM tb_name WHERE id=100001;
SELECT * FROM tb_name WHERE name='哈哈';
SELECT * FROM tb_name WHERE id<1000089;
IN关键字的查询
SELECT * FROM tb_name WHERE id IN (1,2,3,4) ORDER BY id DESC;
SELECT * FROM tb_name WHERE id NOT IN (1,2,3,4) ORDER BY id DESC;
BETWEN AND 的范围查询
SELECT * FROM tb_name WHERE price BETWEN 2 AND 10;
SELECT * FROM tb_name WHERE price NOT BETWEN 2 AND 10;
LIKE的字符匹配查询
SELECT * FROM tb_name WHERE name LIKE 'b%';
SELECT * FROM tb_name WHERE name LIKE '%g%';
SELECT * FROM tb_name WHERE name LIKE 'b%g';
SELECT * FROM tb_name WHERE name LIKE 'b_';
查询空值
SELECT * FROM tb_name WHERE loc IS NULL;
SELECT * FROM tb_name WHERE loc IS NOT NULL;
带AND的多条件查询语句
SELECT * FROM tb_name WHERE price>10 AND name LIKE '%菜';
SELECT * FROM tb_name WHERE price>10 AND name LIKE '%菜' AND num>0;
带OR的多条件查询
SELECT * FROM tb_name WHERE id IN(1,3,6) OR name LIKE '%菜';
查询结果不重复
SELECT DISTINCT s_id FROM tb_name;
DISTINCT不能部分使用,换句话说,DISTINCT关键字应用所有列而不仅是它后面的第一个指定列。例如,查询3个字段a,b,c,如果不同记录的这3个字段的组合值都不同,则所有记录都会被查询出来。DESC可以部分使用。
对查询结果排序(默认ASC)
单列排序SELECT * FRON tb_name ORDER BY id;
多列排序SELECT * FROM tb_name ORDER BY id,name;
多列排序相当一第一列有相同的列值,每个列值分组各自按照第二列进行排序,没有相同则第二列不在排序
指定排序方向SELECT * FROM tb_name ORDER BY id DESC;
多列各自不同方向排序SELECT * FROM tb_name ORDER BY id DESC,name ASC;
如果多列都进行降序,则DESC放最后即可。
LIMIT关键字
前四行记录 SELECT * FROM tb_name LIMIT 4;
从第5行开始,行数长度为3SELECT * FROM tb_name LIMIT 4,3;
****分组查询****
①创建分组
GROUP BY关键字通常和集合函数一起使用,如MAX(),MIN(),COUNT(),SUM(),AVG()。例如,要返回每个水果供应商提供的水果种类,这是就要在分组过程中用到COUNT()函数。
SELECT id,COUNT(*) AS total FROM tb_name GROUP BY id;
如果将每个水果供应商的水果名称显示出来,sql语句如下:
SELECT s_id, GROUP_CONCAT(f_name) AS Names FROM tb_name GROUP BY s_id;
②使用HAVING过滤分组
HAVING和WHERE都是过滤,但是HAVING实在数据分组之后进行过滤来选择分组,二WHERE在分组之前用来选择记录。而且WHERE排除的记录不再包括在分组中。
SELECT s_id, GROUP_CONCAT(f_name) AS Names FROM tb_name GROUP BY s_id HAVING COUNT(f_name)>1;
分组后并显示水果种类大于1的分组信息。
③在GROUP BY子句中使用WITH ROLLUP,作用是在所有查询出的分组记录之后增加一条记录,该记录计算查询出的所有记录的总和,即统计记录数量。
SELECT s_id ,COUNT(*) AS total FROM tb_name GROUP BY s_id WITH ROLLUP;
④多字段分组,分级分组
SELECT * FROM tb_name GROUP BY s_id,f_name;
查询记录先按照s_id进行分组,再对f_name字段按不同的取值进行分组.
⑤GROUP BY和ORDER BY一起使用
SELECT o_num,SUM(quantity*item_price) AS orderTotal FROM tb_name GROUP BY o_num HAVING SUM(quantity*item_price)>=100 ORDER BY orderTotal;