在数据库中创建表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
--创建Person表
CREATE TABLE Person(
PersonID INT PRIMARY KEY,
FirstName VARCHAR(20),
LastName VARCHAR(20)
);
--插入数据
INSERT INTO Person(PersonId,FirstName,LastName) VALUES(1,'JIELUN','ZHOU');
INSERT INTO Person(PersonId,FirstName,LastName) VALUES(1,'JUNJIE','LIN');
INSERT INTO Person(PersonId,FirstName,LastName) VALUES(1,'YIXUN','CHEN');
--创建Address表
CREATE TABLE Address(
AddressId INT PRIMARY KEY,
PersonId INT,
City VARCHAR(20),
State VARCHAR(20)
);
--插入数据
INSERT INTO address(AddressId,PersonId,City,State) VALUES(1,1,'Taiwan','CHina');
INSERT INTO address(AddressId,PersonId,City,State) VALUES(2,2,'Singapore','Singapore');
INSERT INTO address(AddressId,PersonId,City,State) VALUES(3,3,'HongKong','CHina');
--使用LEFT JOIN连接两表
SELECT Person.FirstName, Person.LastName, Address.City,Address.State
FROM Person
LEFT JOIN Address
ON Person.PersonId = Address.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 NOT NULL PRIMARY KEY,
Email VARCHAR(20)
);
--插入数据
INSERT INTO email(Id,Email) VALUES(1,'[email protected]'),(2,'[email protected]'0),(3,'[email protected]');
--删除重复数据
DELETE a
FROM email a,email b
WHERE (a.Email=b.Email AND a.Id > b.Id)
--调出表格内容
SELECT * FROM email;