+ -
当前位置:首页 → 问答吧 → 菜鸟问一条SQL语句

菜鸟问一条SQL语句

时间:2011-10-09

来源:互联网

假设有两个表

Person:
( Name Char(20)
  ID Char(9)
)

Student:
(StudentID
 Grade
 导师ID
)
Person 表包括所有人员的ID和name. 
查询结果需要: 学生的姓名,grade, 学生导师的姓名

请问怎样通过 StudentID, 导师ID, Person.ID 来查询

不胜感激

作者: aidings   发布时间: 2011-10-09

(不要高估你的汉语表达能力或者我的汉语理解能力)
  建议你列出你的表结构,并提供测试数据以及基于这些测试数据的所对应正确结果。
  参考一下这个贴子的提问方式http://topic.csdn.net/u/20091130/20/8343ee6a-417c-4c2d-9415-fa46604a00cf.html
   
  1. 你的 create table xxx .. 语句
  2. 你的 insert into xxx ... 语句
  3. 结果是什么样,(并给以简单的算法描述)
  4. 你用的数据库名称和版本(经常有人在MS SQL server版问 MySQL)
   
  这样想帮你的人可以直接搭建和你相同的环境,并在给出方案前进行测试,避免文字描述理解上的误差。

 

作者: ACMAIN_CHM   发布时间: 2011-10-09


create table Person (
Name char (20),
ID char (9) not null,
Primary key (ID));

insert into Person "Bob" , "0001"
insert into Person "Tom" , "0002"
insert into Person "Katy" , "0003"

create table Student (
StudentID char (9) not null,
GPA double,
MentorID char (9),
Primary key (StudentID));

insert into Student "0001", 3, "0003";
insert into Student "0002", 2, "0003";

想要得到的就结果:

studentName GPA mentorName
  Bob 3 Katy
  Tom 2 Katy

作者: aidings   发布时间: 2011-10-09

SQL code
SELECT p1.Name AS studentName,
       s.GPA,
       p2.Name AS mentorName
  FROM Student s,
       Person p1,
       Person p2
 WHERE s.StudentID = p1.ID
   AND s.MentorID = p2.ID

如果可能出现数据不完整,或者没有导师的情况,考虑用左外联

作者: shine333   发布时间: 2011-10-09

热门下载

更多