查询数据

一、单表查询
1,查询所有字段
SELECT * FROM tb_name;
2,查询指定字段
SELECT id,name FROM tb_name;
3,查询指定记录
SELECT name,loc FROM tb_name WHERE id=6;
4,查询带[NOT] IN关键字的记录
SELECT name,age FROM tb_name WHERE id [NOT] IN(3,6,9) ORDER BY name;
5,查询范围BETWEEN AND
SELECT name,age FROM tb_name WHERE id BETWEEN 2 AND 10;
6,匹配查询LIKE
SELECT id,name FROM tb_name WHERE name LIKE 'ja%';
7,查询空值
SELECT id,name,email FROM tb_name WHERE email [NOT] IS NULL;
8,带AND[OR]的查询
SELECT id,name FROM tb_name WHERE id='110' AND[OR] price>5;
9,查询结构不重复
SELECT DISTINCT name FROM tb_name;
10,对查询结构排序
SELECT name FROM tb_name ORDER BY name [DESC];
SELECT name,price FROM tb_name ORDER BY name,price [DESC];
11,分组查询
SELECT id,COUNT() AS Total FROM tb_name GROUP BY id;
12,使用HAVING过滤分组
SELECT id,GROUP_CONCAT(name) AS Names FROM tb_name
GROUP BY id HAVING COUNT(name)>1;
13,统计记录数量WITH ROLLUP
SELECT id,COUNT(
) AS Total FROM tb_name GROUP BY id WITH ROLLUP;
14,GROUP BY和ORDER BY一起使用
SELECT num,SUM(qtyitem_price) AS total FROM tb_name
GROUP BY num HAVING total>=100
ORDER BY total;
15,限制查询结果数量
SELECT * FROM tb_name LIMIT 4;
二、多表查询
16,内连接查询:使用比较运算符进行表间某些列数据的比较操作,并列出这些表中与连接条件相匹配的数据行。
SELECT t1.id,name,price FROM tb1 INNER JOIN tb2 ON tb1.id=tb2.id;
17,外连接查询:查询左表、右表或两表全部的数据行。
SELECT t1.id,t2.num FROM t1 [LEFT|RIGHT] OUTER JOIN t2 ON t1.id=t2.id;
三、子查询
18,一些带关键字子查询
SELECT num1 FROM tb WHER num1>ANY(SELECT num2 FROM tb2);
SELECT num1 FROM tb WHER num1>ALL(SELECT num2 FROM tb2);
SELECT num1 FROM tb WHER EXISTS(SELECT num2 FROM tb2 WHERE id=2);
SELECT num1 FROM tb WHER num1 IN (SELECT num2 FROM tb2);
19,带运算符的子查询
SELECT id,name from tb1 WHERE id=
(SELECT s1.id FROM stb AS s1 WHERE s1.city='bj');
20,合并查询结果
SELECT id,name,price FROM tb1 WHERE price<9
UNION ALL--不删除重复行,所需资源少,效率高
SELECT id,name,price FROM tb1 WHERE id IN(10,11);
21,使用正则表达式查询
SELECT * FROM fruits WHERE name REGXP='^b';--以b开头
SELECT * FROM fruits WHERE name REGXP='b$';--以b结尾
SELECT * FROM fruits WHERE name REGXP='a.g';--a,g之间有任意字符
SELECT * FROM fruits WHERE name REGXP='ba
';--以a出现过任意次
SELECT * FROM fruits WHERE name REGXP='ba+';--以a出现至少一次
SELECT * FROM fruits WHERE name REGXP='on|ap';--包含字母on和ap
(SELECT * FROM fruits WHERE name LIKE 'on';--只有字母on)
SELECT * FROM fruits WHERE name REGXP='[aop]';--包含字母aop中的任意一个或多个
SELECT * FROM fruits WHERE name REGXP='[^aop]';--不包含字母aop中的任意一个或多个
SELECT * FROM fruits WHERE name REGXP='x[2,]';--x出现至少2次
SELECT * FROM fruits WHERE name REGXP='ba[1,3]';--ba出现1~3次

你可能感兴趣的:(查询数据)