MySQL基础练习(二)
第一个例子我们编写一个 SQL 查询,列出所有超过或等于5名学生的课。
先建表
CREATE TABLE courses( student VARCHAR(10) NOT NULL, class VARCHAR(10) NOT NULL );
再插入数据
INSERT INTO courses VALUES ("A","Math"), ("B","English"), ("C","Math"), ("D","Biology"), ("E","Math"), ("F","Computer"), ("G","Math"), ("H","Math"), ("I","Math"), ("A","Math");
我们要查询所有超过或等于5名学生的课。
SELECT class FROM courses GROUP BY(class) HAVING COUNT(student)>=5;
交换工资
第二个例子交换工资,同样 先建表
CREATE TABLE salary(id INT PRIMARY KEY, NAME VARCHAR(10) NOT NULL, sex VARCHAR(10) NOT NULL, salary INT) NOT NULL );
再插入数据
INSERT INTO salary VALUES (1,"A","m",2500), (2,"B","f",1500), (3,"C","m",5500), (4,"D","f",500);
我们需要交换 f 和 m
UPDATE salary SET sex= CASE sex WHEN 'm' THEN 'f' ELSE 'm' END;
这样就交换成功了
表的连接
先建表,我建了下面的两个表
我们需要编写一个 SQL 查询,满足条件:无论 person 是否有地址信息,都需要基于上述两表提供 person 的以下信息:FirstName, LastName, City, State
select person.FirstName,person.LastName,address.City,address.State from person left join address on person.PersonID=address.PersonID;
删除重复的邮箱
我们用上次已经建好的email表
delete t1 from email t1, email t2 where t1.Email=t2.Email AND t1.Id>t2.Id;