时间:2023-10-27来源:系统城装机大师作者:佚名
提示: 利用单表简单查询和多表高级查询技能,并且根据查询要求灵活使用内连接查询、外连接查询或子查询等。同时还利用内连接查询的两种格式、三种外连接查询语法格式和子查询的语法格式。
内连接查询(不同表之间查询)
方法一
| 1 2 3 4 |
USE XSCJGOSELECT student.sno,sname,cno,grade from student,scwhere student.sno=sc.sno |

方法二
| 1 2 3 4 |
USE XSCJGOSELECT student.sno,sname,cno,grade from student join sc on student.sno=sc.sno |

方法一
| 1 2 3 |
USE XSCJselect student.sno,sname from student,sc,coursewhere student.sno=sc.sno and sc.cno=course.cno and cname='数据库原理与应用' |

方法二
| 1 2 3 |
select student.sno,sname from student join sc on student.sno=sc.sno join course on sc.cno=course.cnowhere cname='数据库原理与应用' |

| 1 2 3 |
select x.sno,sname,cno,gradefrom student x,sc ywhere x.sno=y.sno |

自身连接查询
| 1 2 3 |
select A.sname,A.ssex,A.sagefrom student A,student Bwhere B.sname='张文宝' and A.sage>B.sage |

使用第二种格式实现内连接查询(JOIN ON)
| 1 2 3 |
SELECT student.sno,sname,cno,gradefrom student join scon student.sno=sc.sno |

外连接(左外连接)
| 1 2 3 |
SELECT student.sno,sname,cno,gradefrom student left outer join scon student.sno=sc.sno |

右外连接
| 1 2 3 |
select sc.sno,sname,cno,gradefrom sc right outer join studenton student.sno=sc.sno |

| 1 2 3 |
select sc.sno,course.cno,cname,creditfrom sc right outer join courseon course.cno=sc.cno |

全外连接
| 1 2 3 |
select *from sc full outer join student on student.sno=sc.sno |

UNION联合查询
| 1 2 3 |
select sdept from student where sage='19'unionselect sdept from student where sage='20' |

| 1 2 3 |
select sdept from student where sage='19'union allselect sdept from student where sage='20' |

使用IN或NOT IN 的子查询
| 1 2 3 4 |
select sno,snamefrom studentwhere sno in(select sno from sc) |

改为连接查询实现
| 1 2 3 |
select distinct student.sno,snamefrom student join scon student.sno=sc.sno |

使用比较运算符的子查询
| 1 2 3 4 |
select sno,sname,sagefrom student where sage>(select AVG(sage) from student) |

使用ANY或ALL的子查询
| 1 2 3 4 5 6 |
select sname,sagefrom studentwhere sage>any (select sage from student where sdept='CS') AND sdept!='CS'select * from student |

使用EXISTS的子查询
| 1 2 3 4 |
select *from coursewhere exists(select * from sc where course.cno=sc.cno) |

| 1 2 3 4 |
select *from coursewhere not exists(select * from sc where course.cno=sc.cno) |

查看course表

抽取数据到另一个表
| 1 2 3 4 5 |
select *into tempfrom student where sdept='CS'select * from temp |

INSERT语句中的子查询
| 1 2 3 |
INSERT INTO SCL(sno,cno)select sno,cnofrom student,course |


UPDATE 语句中的子查询
| 1 2 3 4 5 |
UPDATE scset grade=grade+5where cno=(select cno from course where sc.cno=course.cno and cname='前台页面设计') |

删除语句中的子查询
| 1 2 3 4 |
delete from sc where cno= (select cno from course where sc.cno=course.cno and cname='前台页面设计') |

到此这篇关于SQL Server数据库连接查询和子查询的文章就介绍到这了
2023-10-27
windows11安装SQL server数据库报错等待数据库引擎恢复句柄失败解决办法2023-10-27
SQL Server截取字符串函数操作常见方法2023-10-27
浅谈SELECT *会导致查询效率低的原因收缩数据文件通过将数据页从文件末尾移动到更靠近文件开头的未占用的空间来恢复空间,在文件末尾创建足够的空间后,可取消对文件末尾的数据页的分配并将它们返回给文件系统,本文给大家介绍SQL Server 数据库中的收缩数据...
2023-10-27