1. 程式人生 > 其它 >MySQL查詢語句使用

MySQL查詢語句使用

一、在school資料庫中建立四個表:

student/teacher/course/score

mysql> create table student(
    -> sno varchar(20) primary key,
    -> sname varchar(20)not null,
    -> ssex varchar(10)not null,
    -> sbirthday datetime,
    -> class varchar(20)
    -> );
Query OK, 0 rows affected (0.01 sec)

mysql>
create table teacher( -> tno varchar(20) primary key, -> tname varchar(20) not null, -> tsex varchar(20) not null, -> tbirthday datetime, -> prof varchar(20) not null, -> depart varchar(20) not null -> ); Query OK, 0 rows affected (0.01 sec) mysql> create
table course( -> cno varchar(20) primary key, -> cname varchar(20) not null, -> tno varchar(20) not null, -> foreign key(tno) references teacher(tno) -> ); Query OK, 0 rows affected (0.01 sec) mysql> create table score( -> sno varchar(20) not null, -> cno varchar
(20) not null, -> degree decimal, -> foreign key(sno) references student(sno), -> foreign key(cno) references course(cno), -> primary key(sno,cno) -> ); Query OK, 0 rows affected (0.02 sec)

二、插入資料

insert into 表名 values();

三、查詢資料

1.查詢student表中所有記錄sname,ssex,class列:

selectsname,ssex,class from student;

2.查詢教師所有單位中不重複的depart列:(distinct排除重複)

select distinct depart from teacher;

3.查詢score表中成績在60~80之間的所有記錄:(查詢區間between..and../直接使用運算子比較)

select *from score where degree between 60 and 80;

或select *from score where degree>60 and degree<80;

4.查詢score表中成績為85,86或88的記錄:(表示或者關係的查詢 in)

select *from score where degree in(85,86,88);

5.查詢student表中“95031”班或性別為女的同學記錄:

select *from student where class='95031' or ssex='女';

6.以class降序查詢student表的所有記錄:(升序asc/降序desc)

select *from student order by class desc;

預設是升序所以一般不會寫

7.以cno升序、degree降序查詢score表的所有記錄:

select *from score order by cno asc,degree desc;

8.查詢“95031”班的學生人數:(統計count)

select count(*) from student where class='95031';

9.查詢score表中的最高分的學生學號和課程號:(子查詢或者排序)

select sno,cno from score where degree=(select max(degree) from score);