一、題目名稱sql
Combine Two Tables(跨表查詢)數據庫
二、題目地址spa
https://leetcode.com/problems/combine-two-tables/命令行
三、題目內容code
如今有兩張表Person和Address,它們的表結構以下:leetcode
表Person:get
+-------------+---------+ | Column Name | Type | +-------------+---------+ | PersonId | int | | FirstName | varchar | | LastName | varchar | +-------------+---------+
表Address:it
+-------------+---------+ | Column Name | Type | +-------------+---------+ | AddressId | int | | PersonId | int | | City | varchar | | State | varchar | +-------------+---------+
寫一個SQL語句,查出每一個人的下列信息:FirstName, LastName, City, Statetable
四、初始化數據庫腳本ast
在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, '南陽', '荊州');
五、解題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