1、题目名称
Combine Two Tables(跨表查询)
2、题目地址
https://leetcode.com/problems/combine-two-tables/
3、题目内容
现在有两张表Person和Address,它们的表结构如下:
表Person:
+-------------+---------+ | Column Name | Type | +-------------+---------+ | PersonId | int | | FirstName | varchar | | LastName | varchar | +-------------+---------+
表Address:
+-------------+---------+ | Column Name | Type | +-------------+---------+ | AddressId | int | | PersonId | int | | City | varchar | | State | varchar | +-------------+---------+
写一个SQL语句,查出每个人的下列信息:FirstName, LastName, City, State
4、初始化数据库脚本
在MySQL数据库中建立一个名为LEETCODE的数据库,用MySQL命令行中的source命令执行下面脚本:
-- 执行脚本前必须建立名为LEETCODE的DATABASE USE LEETCODE; DROP TABLE IF EXISTS Person; CREATE TABLE Person ( PersonId INT NOT NULL PRIMARY KEY, FirstName VARCHAR(50), LastName VARCHAR(50) ); INSERT INTO Person (PersonId, FirstName, LastName) VALUES (1, ‘羽‘, ‘关‘); INSERT INTO Person (PersonId, FirstName, LastName) VALUES (2, ‘飞‘, ‘张‘); INSERT INTO Person (PersonId, FirstName, LastName) VALUES (3, ‘超‘, ‘马‘); INSERT INTO Person (PersonId, FirstName, LastName) VALUES (4, ‘云‘, ‘赵‘); INSERT INTO Person (PersonId, FirstName, LastName) VALUES (5, ‘忠‘, ‘黄‘); INSERT INTO Person (PersonId, FirstName, LastName) VALUES (6, ‘延‘, ‘魏‘); DROP TABLE IF EXISTS Address; CREATE TABLE Address ( AddressId INT NOT NULL PRIMARY KEY, PersonId INT, City VARCHAR(50), State VARCHAR(50) ); INSERT INTO Address (AddressId, PersonId, City, State) VALUES (11, 1, ‘解良‘, ‘河东‘); INSERT INTO Address (AddressId, PersonId, City, State) VALUES (22, 2, ‘涿郡‘, ‘幽州‘); INSERT INTO Address (AddressId, PersonId, City, State) VALUES (33, 3, ‘茂陵‘, ‘扶风‘); INSERT INTO Address (AddressId, PersonId, City, State) VALUES (44, 4, ‘真定‘, ‘常山‘); INSERT INTO Address (AddressId, PersonId, City, State) VALUES (55, 5, ‘南阳‘, ‘荆州‘);
5、解题SQL
解决本问题的SQL其实非常简单,使用 LEFT JOIN 跨两个表查询一下就可以了,SQL语句如下:
SELECT A.FIRSTNAME, A.LASTNAME, B.CITY, B.STATE FROM Person AS A LEFT JOIN Address AS B ON A.PERSONID = B.PERSONID;
需要注意的是,不能使用下面这条SQL语句:
SELECT A.FirstName, A.LastName, B.City, B.State FROM Person AS A, Address AS B WHERE A.PersonId = B.PersonId;
原因是因为当Person表中有条目,而Address表中没有时,条目就无法被这条SQL查询到了,而事实上在Person表中有的条目应该被全部查询出来。
两个SQL语句查询结果的不同之处可以从查询结果中看出:
可以看到,第一条SQL语句可以查出魏延,第二条不能查出。
END
时间: 2024-10-19 19:40:26