当数据来源于不同表时
内连接 inner join 查询两个表中结果集中的交集
SELECT g.GradeName ,s.StudentName FROM grade g INNER JOIN student s
ON g.GradeID
=s.GradeId
WHERE g.GradeName=‘大一’;
select g.gradename ,s.studentname from grade g,student s where g.gradeid=s.gradeid and gradename=‘大一’; 这种会消耗大量资源,笛卡尔积,s*g的数量里找
SELECT studentname,subjectname,score FROM result r
JOIN student s
ON r.`stu_id`=s.`StudentNo`
JOIN SUBJECT su
ON r.`sub_no`=su.`SubjectNo`;
外连接 outer join
左外连接 left join 以左表为基准,右表一一匹配,匹配不上的返回坐左表的记录,右表以null填充
右外连接 right join 以右表为基准,左表一一匹配,匹配不上的返回坐右表的记录,左表以null填充
SELECT studentname ,score FROM student s
LEFT JOIN result r
ON s.`StudentNo`=r.`stu_id`;
SELECT studentname ,score FROM student s
RIGHT JOIN result r ON s.`StudentNo`=r.`stu_id`;
union:联合并去重
union all:联合不去重
#全连接
SELECT studentname ,score FROM student s
LEFT JOIN result r ON s.`StudentNo`=r.`stu_id`
UNION
SELECT studentname ,score FROM student s
RIGHT JOIN result r ON s.`StudentNo`=r.`stu_id`;
即自己连接自己
CREATE TABLE IF NOT EXISTS category(
category_id INT(11) AUTO_INCREMENT PRIMARY KEY,
category_name VARCHAR(10),
pid INT(10)
);
ALTER TABLE category MODIFY category_name VARCHAR(50);
INSERT INTO category(category_name,pid)
VALUES('软件开发',0),('美术设计',0),('数据库基础',1),
('photoshop基础',2),('色彩搭配学',2),('php基础',1),
('一起学java',1);
SELECT * FROM category;
SELECT a.category_name,b.category_name FROM category a
JOIN category b ON b.pid=a.category_id AND a.pid=0;