【mysql学习】day4
作业五:
组合两张表 (难度:简单)
在数据库中创建表1和表2,并各插入三行数据(自己造)
表1: Person
±------------±--------+
| 列名 | 类型 |
±------------±--------+
| PersonId | int |
| FirstName | varchar |
| LastName | varchar |
±------------±--------+
PersonId 是上表主键
表2: Address
±------------±--------+
| 列名 | 类型 |
±------------±--------+
| AddressId | int |
| PersonId | int |
| City | varchar |
| State | varchar |
±------------±--------+
AddressId 是上表主键
编写一个 SQL 查询,满足条件:无论 person 是否有地址信息,都需要基于上述两表提供 person 的以下信息:FirstName, LastName, City, State
CREATE TABLE Person(
PersonId INT NOT NULL,
FirstName VARCHAR(30) NOT NULL,
LastName VARCHAR(30) NOT NULL
);
ALTER TABLE Person MODIFY PersonId INT PRIMARY KEY;
-- 插入数据
INSERT INTO Person VALUES(1,"Alfonso","Carlos");
INSERT INTO Person VALUES(2,"Antonio","Julio");
INSERT INTO Person VALUES(3,"Belen","Sonia");
-- 创建表Address
CREATE TABLE Address(
AddressId INT PRIMARY KEY,
PersonId INT,
City VARCHAR(20),
State VARCHAR(20)
);
-- 插入数据
INSERT INTO Address VALUES(1,1,"Hangzhou","China");
INSERT INTO Address(AddressId,PersonId) VALUES(2,2);
INSERT INTO Address VALUES(3,3,"NewYork","American");
-- 作业解答
SELECT p.FirstName,p.LastName,a.City,a.State
FROM Person p LEFT JOIN Address a
ON p.PersonId = a.PersonId
作业六:
删除重复的邮箱(难度:简单)
编写一个 SQL 查询,来删除 email 表中所有重复的电子邮箱,重复的邮箱里只保留 Id 最小 的那个。
±—±--------+
| Id | Email |
±—±--------+
| 1 | [email protected] |
| 2 | [email protected] |
| 3 | [email protected] |
±—±--------+
Id 是这个表的主键。
例如,在运行你的查询语句之后,上面的 Email表应返回以下几行:
±—±-----------------+
| Id | Email |
±—±-----------------+
| 1 | [email protected] |
| 2 | [email protected] |
±—±-----------------+
CREATE TABLE email(
id INT PRIMARY KEY,
Email VARCHAR(50) NOT NULL
);
-- 插入数据
INSERT INTO email VALUES(1,"[email protected]");
INSERT INTO email VALUES(2,"[email protected]");
INSERT INTO email VALUES(3,"[email protected]");
-- 自连接
DELETE e1
FROM email e1,email e2
WHERE e1.Email = e2.Email
AND e1.id > e2.id;
-- 查询结果
select * from email;
上一篇: java学习day4