Get a record of one fields and also of the Foreign Key
I have two tables CountryMaster
and StatesMaster
开发者_JAVA百科. The fields are:
CountryMaster(CountryId, Name)
StateMaster(StateId, Name, CountryId)
The StateMaster.CountryId
is a Foreign key. I want to get the Name
of States
from StateMaster
as well as the Name
of the Country
to which that State belongs from CountryMaster
.
I want this in one query. How can i get this?
SELECT
s.Name AS StateName
, c.Name AS CountryName
FROM
dbo.StateMaster s
INNER JOIN
dbo.CountryMaster c
ON c.CountryId = s.CountryId
Join Fundamentals
By using joins, you can retrieve data from two or more tables based on logical relationships between the tables. Joins indicate how Microsoft SQL Server should use data from one table to select the rows in another table.
A join condition defines the way two tables are related in a query by:
Specifying the column from each table to be used for the join. A
typical join condition specifies a foreign key from one table and its associated key in the other table.
Specifying a logical operator (for example, = or <>,) to be used
in comparing values from the columns.
Inner joins can be specified in either the FROM or WHERE clauses. Outer joins can be specified in the FROM clause only. The join conditions combine with the WHERE and HAVING search conditions to control the rows that are selected from the base tables referenced in the FROM clause.
精彩评论