A data join is a technique of creating a list of records from more that one table, using all columns from all tables involved, or selecting only the desired columns from one or all of the tables involved. This means that a data join is essentially created in three steps:
Before creating a join, you must have the tables that would be involved. The tables are created using the techniques we have seen in previous lessons. It is also important to create a primary key for each table. The parent table would usually need only this primary key that would be used to "link" it to a child table. If needed, you can then create the necessary records for the table. Here is an example: CREATE TABLE Genders ( GenderID int identity(1, 1) not null, Gender nchar(15), CONSTRAINT PK_Genders PRIMARY KEY(GenderID) ); GO INSERT INTO Genders(Gender) VALUES(N'Male'),(N'Female'),(N'Unknown'); GO When creating the child table, remember to create a column that would serve as the link with the parent table. By a (good) habit as we saw when studying relationships, the name and the data type of this column are the same as the primary key of the parent table. Here is an example: -- =================================================== -- Database: People -- Author: FunctionX -- Date Created: Tuesday, July 28, 2009 -- =================================================== IF EXISTS(SELECT name FROM sys.databases WHERE name = N'People') DROP DATABASE People; GO CREATE DATABASE People; GO USE People; GO IF OBJECT_ID('Genders', 'U') IS NOT NULL DROP TABLE Genders GO -- =================================================== -- Database: People -- Table: Genders -- Author: FunctionX -- Date Created: Tuesday, July 28, 2009 -- Description: This table holds the list of genders -- =================================================== CREATE TABLE Genders ( GenderID int identity(1, 1) not null, Gender nchar(15), CONSTRAINT PK_Genders PRIMARY KEY(GenderID) ); GO INSERT INTO Genders(Gender) VALUES(N'Male'),(N'Female'),(N'Unknown'); GO -- =================================================== -- Database: People -- Table: Persons -- Author: FunctionX -- Date Created: Tuesday, July 28, 2009 -- Description: This table holds a list of people -- and their genders -- =================================================== CREATE TABLE Persons ( PersonID int identity(1, 1) not null, FirstName nvarchar(20), LastName nvarchar(20), GenderID int, CONSTRAINT PK_Persons PRIMARY KEY(PersonID) ); GO INSERT INTO Persons(FirstName, LastName, GenderID) VALUES(N'John', N'Franks', 1), (N'Peter', N'Sonnens', 1); GO INSERT INTO Persons(FirstName, LastName) VALUES(N'Leslie',N'Aronson'); GO INSERT INTO Persons(FirstName, LastName, GenderID) VALUES(N'Mary', N'Shamberg', 2), (N'Chryssa', N'Lurie', 2), (N'Hellah', N'Zanogh', 3), (N'Olympia', N'Sumners', 2), (N'Roberta', N'Jerseys', 2); GO INSERT INTO Persons(FirstName, LastName) VALUES(N'Hel�ne', N'Campo'); GO INSERT INTO Persons(LastName, GenderID) VALUES(N'Millam', 1), (N'Hessia', 2); GO INSERT INTO Persons(FirstName, LastName, GenderID) VALUES(N'Stanley', N'Webbs', 2), (N'Arnie', N'Ephron', 3), (N'Mike', N'Pastore', 1); GO INSERT INTO Persons(FirstName) VALUES(N'Salim'); GO INSERT INTO Persons(FirstName, LastName, GenderID) VALUES(N'Mary', N'Shamberg', 2), (N'Chryssa', N'Lurie', 2); GO INSERT INTO Persons(LastName) VALUES(N'Millers'); GO INSERT INTO Persons(FirstName, GenderID) VALUES(N'Robert', 1); GO
Equipped with the necessary tables and their columns, you can create the join. To do this in the SQL Server Management Studio, in the Object Explorer, right-click the database and click open a Query window. Then:
Any of these actions would display the Table window:
Because the foundation of a join lies on at least two tables, you should add them. To do this, you use the Add Table dialog box. If you had closed the Add Table dialog box, you can right-click the top section of the Query Designer and click Add Table... On the Add Table dialog box:
After adding the tables, click Close. Here is an example of two tables that have been added:
If a relationship was already established between the tables, a joining line would show it. In the SQL, the basic formula to create a join is: SELECT WhatColumn(s) FROM ChildTable TypeOfJoin ParentTable ON Condition ChildTable specifies the table that holds the records that will be retrieved. It can be represented as follows: SELECT WhatColumn(s) FROM Persons TypeOfJoin ParentTable ON Condition ParentTable specifies the table that holds the column with the primary key that will control what records, related to the child table that will display. This would be represented as follows: SELECT WhatColumn(s) FROM Persons TypeOfJoin Genders ON Condition Condition is a logical expression used to validate the records that will be isolated. The condition can be created using the following formula: Table1Column Operator Table2Column To create the condition, you start with the ON kyword. You can assign the primary key column of the parent table to the foreign key column of the child table. Because both columns likely have the same name, to distinguish them, their names should be qualified. This would be done as follows: SELECT WhatColumn(s) FROM Persons TypeOfJoin Genders ON Persons.GenderID = Genders.GenderID Although we used the assignment operator "=", another operator, such as LIKE, can also be used, as long as it can be used to assign one column to another. Here is an example: SELECT WhatColumn(s) FROM Persons TypeOfJoin Genders ON Persons.GenderID LIKE Genders.GenderID The WhatColumn(s) of our formula allows you to make a list of the columns you want to include in your statement. As you should be aware, you can include all columns by using the * operator. Here is an example: SELECT * FROM Persons TypeOfJoin Genders ON Persons.GenderID = Genders.GenderID In this case, all columns from all tables would be included in the result. Instead of all columns, you may want a restricted list. In this case, create the list after the SELECT keyword separating them with commas. You can use the name of a column normally if that name is not duplicated in more than one column. Here is an example: SELECT LastName, FirstName, Gender FROM Persons TypeOfJoin Genders ON Persons.GenderID = Genders.GenderID If the same name of a column is found in more than one table, as is the case for a primary-foreign key combination, you should qualify the name. Here is an example: SELECT LastName, FirstName, Persons.GenderID, Genders.GenderID, Gender FROM Persons TypeOfJoin Genders ON Persons.GenderID = Genders.GenderID In fact, to make your code easier to read, you should qualify the name of each column of your SELECT statement. Here is an example: SELECT Persons.LastName, Persons.FirstName, Persons.GenderID, Genders.GenderID, Genders.Gender FROM Persons TypeOfJoin Genders ON Persons.GenderID = Genders.GenderID If you have a schema, you can use it to qualify a (each) table. Here is an example: SELECT dbo.Persons.LastName, dbo.Persons.FirstName, dbo.Persons.GenderID, dbo.Genders.GenderID, dbo.Genders.Gender FROM dbo.Persons TypeOfJoin dbo.Genders ON dbo.Persons.GenderID = dbo.Genders.GenderID You can also use an alias name for each table. Here is an example: SELECT pers.LastName, pers.FirstName, pers.GenderID, Genders.GenderID, Genders.Gender FROM Persons pers TypeOfJoin Genders ON pers.GenderID = Genders.GenderID
When studying data relationships, we saw the role of the primary and foreign keys in maintaining the exchange of information between two tables. This technique of linking tables plays a major role when creating a join. It allows you to decide whether you want to include all records or only isolate some of them. To respect the direction of a relationship between two tables as it is applied to a query, Transact-SQL supports three types of joins. A cross join creates a list of all records from both tables as follows: the first record from the parent table is associated to each record from the child table, then the second record from the parent table is associated to each record from the child table, and so on. In this case also, there is no need of a common column between both tables. In other words, you will not use the ON clause. To create a cross join, you can replace the TypeOfJoin of our formula with CROSS JOIN or CROSS OUTER JOIN. Here is an example: SELECT Persons.PersonID, Persons.FirstName, Persons.LastName, Genders.GenderID, Genders.Gender FROM Persons CROSS JOIN Genders GO By default, in the SQL Server Management Studio, after you have just added a table to another one (if no relationship was already established between both tables), the query would be automatically made a cross join. All you have to do is to select the necessary columns:
After selecting the columns, you can click OK and execute the query to see the result:
Imagine you have two tables that can be linked through one's primary key and another's foreign key:
Notice that some records in the Persons table don't have an entry for the GenderID column and were marked with NULL by the database engine. When creating a query of records of the Persons table, if you want your list to include only records that have an entry, you can create it as inner join. By default, from the SQL Server Management Studio, when creating a new query, if a relationship was already established between both tables, the query is made an inner join. If there was no relationship explicitly established between both tables, you would have to create it or edit the SQL statement. Consider the following:
Notice that, because no relationship is established between both tables, the join is crossed. To create an inner join, you have two options. You can drag the primary key from the parent table and drop it on the foreign key in the child table. Here is an example:
Alternatively, you can edit the SQL statement manually to make it an inner join. To do this, you would specify the TypeOfJoin factor of our formula with the expression INNER JOIN. Here is an example: SELECT Persons.PersonID, Persons.FirstName, Persons.LastName, Persons.GenderID, Genders.GenderID AS [Gender ID], Genders.Gender FROM Persons INNER JOIN Genders ON Persons.GenderID = Genders.GenderID After creating the join, in the Diagram pane, a line would be created to join the tables:
You can then execute the query to see the result. This would produce:
We mentioned earlier that you could include all columns in the query. In our result, since we are more interested in the gender of each Persons record, we would not need the GenderID column from the Genders table. Here is an example:
As mentioned earlier, notice that the result includes only records that have an entry (a non-NULL entry) in the GenderID foreign key column of the Persons table. An alternative to the INNER JOIN expression is to simply type JOIN. Here is an example: SELECT Persons.PersonID, Persons.FirstName, Persons.LastName, Genders.Gender FROM Persons JOIN Genders ON Persons.GenderID = Genders.GenderID GO To destroy a join between two tables, if you are working in the Table window, you can right-click the line that joins the tables and click Remove. In SQL, you must modify the expressions that make up the join (the JOIN and the ON expressions). |
|
|||||||||||||||||||||||||||
|