Sql Select 来自多个 table
Sql Select From multiple table
我有 3 个 table:
Visitor table
VisitorId (pk)
Name
Phone
Country table
CountryId (pk)
Name
Code
Travels table
TravelId (pk)
CountryId (fk)
VisitorId (fk)
IsVisited (bool)
我想让每个国家/地区在 Travels
table 中创建另一个入口,其中将包含 CountryId
、VisitorId
和 false
IsVisited
.
更新
INSERT INTO Travels (CountryId, VisitorID, IsVisisted)
SELECT Visitor.VisitorId, Country.CountryId, 1 FROM Visitor, Country
你应该写成:
-- STEP2: Insert records:
INSERT INTO @Travels
SELECT CountryId,VisitorId,0 FROM -- 0 = false for IsVisited
(
-- STEP1: first create a combination for all visitor Id and country Id
-- and get all the combinations which are not there in existing Travels table
SELECT C.CountryId,V.VisitorId
FROM @Country C
CROSS JOIN @Visitor V
EXCEPT
SELECT CountryId,VisitorId
FROM @Travels
) AS T
否则,如果您想为 Country
和 Visitor
中的每个组合创建一个条目,请写为:
-- STEP2: Insert records:
INSERT INTO @Travels
SELECT CountryId,VisitorId,0 FROM
(
-- STEP1: first create a combination for all visitor Id and country Id
SELECT C.CountryId,V.VisitorId
FROM @Country C
CROSS JOIN @Visitor V
) AS T
SELECT * FROM @Travels
我有 3 个 table:
Visitor table
VisitorId (pk)
Name
Phone
Country table
CountryId (pk)
Name
Code
Travels table
TravelId (pk)
CountryId (fk)
VisitorId (fk)
IsVisited (bool)
我想让每个国家/地区在 Travels
table 中创建另一个入口,其中将包含 CountryId
、VisitorId
和 false
IsVisited
.
更新
INSERT INTO Travels (CountryId, VisitorID, IsVisisted)
SELECT Visitor.VisitorId, Country.CountryId, 1 FROM Visitor, Country
你应该写成:
-- STEP2: Insert records:
INSERT INTO @Travels
SELECT CountryId,VisitorId,0 FROM -- 0 = false for IsVisited
(
-- STEP1: first create a combination for all visitor Id and country Id
-- and get all the combinations which are not there in existing Travels table
SELECT C.CountryId,V.VisitorId
FROM @Country C
CROSS JOIN @Visitor V
EXCEPT
SELECT CountryId,VisitorId
FROM @Travels
) AS T
否则,如果您想为 Country
和 Visitor
中的每个组合创建一个条目,请写为:
-- STEP2: Insert records:
INSERT INTO @Travels
SELECT CountryId,VisitorId,0 FROM
(
-- STEP1: first create a combination for all visitor Id and country Id
SELECT C.CountryId,V.VisitorId
FROM @Country C
CROSS JOIN @Visitor V
) AS T
SELECT * FROM @Travels