数据库SQL语句-----单表多表连接查询实例

查询所有学生语文科目成绩,按成绩高低排名

SELECT A.ID,A.NAMES,B.SCORE FROM STUDENT A JOIN SCORES B ON A.ID=B.STUDENT_ID WHERE B.SUBJECT_ID='YW' ORDER BY SCORE DESC

UNION ALL 查询

SELECT * FROM SCORES

UNION ALL //并起来,行数与列数必须相同

SELECT * FROM SCORES2

SELECT STUDENT_ID,SUBJECT_ID,SCORE FROM SCORES

UNION ALL

SELECT STUDENT_ID,SUBJECT_ID,SCORE FROM SCORES2

错误查询,列不相同,如:

SELECT * FROM GRADE

UNION ALL

SELECT * FROM SUBJECT

必须保证列数相同,且数据类型一样

SELECT ID FROM GRADE

UNION ALL

SELECT ID FROM SUBJECT

查询2班所有学生数学成绩>60分的记录

SELECT A.ID,A.NAMES,B.SCORE FROM STUDENT A JOIN SCORES B ON A.ID=B.STUDENT_ID WHERE B.SUBJECT_ID='SX' AND A.GRADE_ID='02' AND B.SCORE>60

查询所有学生信息,显示学生姓名,性别,年龄,班级名称,联系方式,住址

SELECT A.NAMES,CASE A.SEX WHEN 1 THEN '男' WHEN 2 THEN '女' ELSE '录入错误' END AS SEX,YEAR(CURRENT //当前年份DATE)-YEAR(DATE(A.BIRTHDAY)//转换成日期类型) AS AGE,B.NAMES,A.MOBILE,A.ADDRESS FROM STUDENT A JOIN GRADE B ON A.GRADE_ID=B.ID

查询所有学生成绩,按照科目排序,没有成绩的学生分数为0

SELECT C.ID,C.NAMES,C.SUBJECTID,COALESCE(D.SCORE,0) FROM (SELECT A.ID,A.NAMES,B.ID AS SUBJECTID FROM STUDENT A,SUBJECT B) C LEFT JOIN SCORES D ON C.ID = D.STUDENT_ID AND C.SUBJECTID= D.SUBJECT_ID

ORDER BY C.SUBJECTID

//coalesce(c.score,备用的字段)判断为备用的

你可能感兴趣的:(数据库SQL语句-----单表多表连接查询实例)