Sql关联查询问题

来源:百度知道 编辑:UC知道 时间:2024/06/26 06:20:17
比如A表是学生

id,
name,
......

B表是成绩

a_id,
subject(表示语文,数学,英语===),
grade,

......

A表的id 字段作为B表 id的外键。

我需要用一个查询语句,用一行显示同一个Id下,语文的grade,数学的grade,英语的grade===。有那位高手可以帮忙解决下,谢谢了。。

没测试过 应该没什么大问题
select c.id,c.subject,sum(chngrade),sum(enggrade),sum(matgrade) from (
select a.id,b.subject,b.grade chngrade,0 enggrade,0 matgrade from a,b
where a.id=b.id and b.subject='语文'
union
select a.id,b.subject,0,b.grade,0 from a,b
where a.id=b.id and b.subject='数学'
union
select a.id,b.subject,0,0,b.grade from a,b
where a.id=b.id and b.subject='英语') c
group by c.id,c.subject

select a.id,sum( case when subject = '语文' then grade else 0) "语文"
, sum(case when subject = '数学' then grade else 0) "数学"
from B,A a
where B.id = a.id;

我写的可以显示 语文和数学
你把英语按照格式写进去试试吧

除了2楼,其他人都连题目都没看清楚
那么容易楼主需要上来问吗

select a.id,a.name,b.chengji from A a,B b where a.id=b.a_id

sql="select a.*,b.* from a ,b where a.id=b.a_id and id=你要查询的学生id"

select A1.id,B1.subject,B1.grade form A A1,B B1 where A1.id = B1.a_id