Mysql---学习笔记<二>

来源:互联网 发布:数据恢复apk 编辑:程序博客网 时间:2024/06/02 06:00

AS子句作为别名
AS子句作用
可给表取一个新的别名
可把经计算或总结的结果用另外一个新名称来代替
AS子句的用法
如:
select studentno as “学号” from student;
select a.studentno from student as a;
select phone+1 as tel from student;
注意:
as也可以省略不写
distinct关键字的使用
distinct关键字 (去掉重复的)
作用:
去掉select查询返回的记录结果中重复的记录(所有返回列的值都相同),只返回一条
语法:
select distinct 字段名1,字段名2,… from 表名
注意:
all关键字的默认的,返回所有的记录。

逻辑操作符:
AND 或 && :逻辑与,同时为真结果为真
语法: a AND b 或 a && b

OR 或 || :逻辑或,只要一个为真则结果为真
语法: a OR b 或 a||b

XOR 或 ^ :逻辑异或,不同为真,相同为假
语法: a XOR b

NOT 或 ! :逻辑非,若操作数为假,结果则为真
语法: NOT a 或 !a

MySql的like语句中的通配符:百分号、下划线和escape

%代表任意多个字符
Sql代码 www.2cto.com
select * from user where username like ‘%huxiao’;

select * from user where username like ‘huxiao%’;

select * from user where username like ‘%huxiao%’;

_代表一个字符
Sql代码
select * from user where username like ‘_’;

select * from user where username like ‘huxia_’;

select * from user where username like ‘h_xiao’;

如果要查%或者,怎么办呢?使用escape,转义字符后面的%或就不作为通配符了,
注意前面没有转义字符的%和_仍然起通配符作用
Sql代码
select username from gg_user where username like ‘%xiao/_%’ escape ‘/’;

select username from gg_user where username like ‘%xiao/%%’ escape ‘/’;

连接查询(多表查询)
连接查询:如需要多张数据表的数据进行查询,则可通过连接运算符实现多个查询。
分类包括:
内连接(inner join)
等值和非等值的连接查询
自身连接查询
外连接(out join)
左连接(LEFT JOIN)
右连接(RIGHT JOIN)

内连接查询:
inner join内连接
在表中至少一个匹配时,则返回记录
select 字段1,字段2,… from table1 inner join table1 on table1.字段X=table2.字段Y;
inner join与join是相同的;
如table1中的行在table2中没有匹配,则不返回;

内连接查询
等值和非等值的连接查询
与表单查询类似,都是SELECT语句;
把多个表放到FROM后,并用逗号隔开;
可使用AS关键字取别名,便于引用;
如无重名查询字段则可省略数据表的指定;
例:
#————————–内连接查询多张表—————————#
#查询学生的姓名及成绩
SELECT s.StudentName,r.StudentResult
FROM student s INNER JOIN result r ON s.StudentNo=r.StudentNo;
#查询学生的姓名及成绩
SELECT student.StudentName,result.StudentResult
FROM student INNER JOIN result ON student.StudentNo=result.StudentNo;
#查询学生的姓名及成绩
SELECT s.StudentName,r.StudentResult
FROM student s JOIN result r ON s.StudentNo=r.StudentNo;

外连接
左外连接(LEFT JOIN)
从左表(table1)中返回所有的记录,即便在右表(table2)中没有
匹配的行;
SELECT 字段1,字段2,…FROM table1 LEFT[OUTER] JOIN table2
ON table1.字段X=table2.字段Y;
右外连接(RIGHT JOIN)
从右表(table2)中返回所有的记录,即便在左表(table1)中没有
匹配的行;
SELECT 字段1,字段2,…FROM table1 RIGHT[OUTER] JOIN table2
ON table1.字段X=table2.字段Y;
例:
#———————-外连接———————–#
SELECT s.StudentNo,s.StudentName,r.StudentResult
FROM student s LEFT JOIN result r ON s.StudentNo=r.StudentNo
WHERE s.StudentNo>1015;

SELECT s.SubjectName,g.GradeName
FROM subject s RIGHT JOIN grade g ON s.GradeID=g.GradeID;

JOIN对比

INNER JOIN(JOIN):如果表中有至少一个匹配,则返回,不匹配的舍去。

LEFT JOIN(左外连接/左连接):即使右表中没有匹配,也从左表中返回所有的行。(左表是完整的)

RIGHT JOIN(右外连接/右连接):即使左表中没有匹配,也从右表中返回所有的行。(右表是完整的)

0 0
原创粉丝点击