当前位置:首页 » 编程语言 » sql三张表查询

sql三张表查询

发布时间: 2024-10-26 17:05:23

A. 三表联查的sql语句

这问题交给我吧,假设学生表叫student,课程表叫class,选课表叫choose
1.三层嵌套的问题
select student.name from student where student.id IN
(select choose.sid from choose where choose.cid NOT IN
(select class.id from class where class.teacher='李明'))
2.一个内连接,一个嵌套
select student.name,avg(choose.score) from
student inner join choose on student.id=choose.sid
where student.id IN
(select choose.sid from choose
where choose.score<'60'
group by choose.sid
having count(choose.sid)>=2)
gruop by student.id
3.一个联合查询,一个嵌套查询
select student.name from student
where student.id IN
(select c1.sid from choose c1 where choose.cid='1'
union
select c2.sid from choose c2 where choose.cid='2'
on c1.sid=c2.sid
)
4.好吧,看起来很难,其实就是自连接查询和行列交换的问题
select student.id,
(case choose.id when '1' then choose.score end) as 1号课成绩,
(case choose.id when '2' then choose.score end) as 2号课成绩,
from student inner join choose on student.id=choose.sid sc1,
student inner join choose on student.id=choose.sid sc2
where sc1.id='1'
and sc2.id='2'
and sc1.score>sc2.score

5.至于你说的insert报错的问题,我想可能是因为学生ID和课程ID这两个外键有重复的值,
你可以检查下,实在不行删除外键,插入数据,在这里外键对你最后要的结果影响不大。

纯手工打造~有帮助记得给分哈

B. 求三表联合查询的SQL查询语句

1、SQL语句:select u.*,r.*,r.id rid

from user u left join sys_user_role sur on u.id = sur.useridleft join sys_role r on sur.roleid = r.id

图片:(表名截图)

  • 算了,建表语句也给你们了,你们自己测试,这样更详细,(程序员)多动手,比什么都好。(这里的 界面 对写代码不太友好,我放博客里了,自己复制粘贴测试使用就行)

    sql语句地址:网页链接

    2、SQL语句解释:

    select a.*,b.*

    from a表 a left join b表 b on a.id = b.aid

    left join c表 c on b.cid = c.id

    注2:此语句适合a表与c表连接,b表是关系表的情况。

C. SQL数据库的表。怎么同时连接3个表查询。

可以参考下面的方法:

1、select * from 表1,表2,表3 where 表1.字段=表2.字段 and 表1.字段=表3.字段

2、select * from 表1 join 表2 on 表1.字段=表2.字段 and join 表3 on 表1.字段=表3.字段

如果没有AND,前面就需要加括号了。

(3)sql三张表查询扩展阅读:

参考语句

创建新表

create table tabname(col1 type1 [not null] [primary key],col2 type2 [not null],..)

根据已有的表创建新表:

1、create table tab_new like tab_old (使用旧表创建新表)

2、create table tab_new as select col1,col2… from tab_old definition only

删除新表

drop table tabname

热点内容
微信猜拳算法 发布:2024-10-26 19:23:35 浏览:390
android编译第三方库 发布:2024-10-26 19:14:20 浏览:615
苹果手机怎么用蓝牙传照片给安卓 发布:2024-10-26 18:57:40 浏览:615
ios8程序加密 发布:2024-10-26 18:30:27 浏览:533
密码门锁没电了用什么数据线 发布:2024-10-26 18:21:11 浏览:855
linuxloop 发布:2024-10-26 18:20:46 浏览:932
linuxvg查看 发布:2024-10-26 18:09:51 浏览:585
图标是钥匙的加密软件 发布:2024-10-26 18:07:31 浏览:625
vip七九宝琉璃怎么配置魂环 发布:2024-10-26 17:51:17 浏览:571
opencv编译linux 发布:2024-10-26 17:49:50 浏览:983