Joins


Joins

If you have more than one table in a query, joining the tables together is imperative. If you do not join tables, you will get a Cartesian (cross) product.
Si una consulta incluye más de una tabla, el uso de las junturas es necesario. Si las tablas no se juntan, el resultado será el producto cruzado de las tablas.

Cross Join

Cross join between two tables gives all possible pairs of rows from two tables. For instance, if a table has 10 rows and another table has 20 rows, the cross join will return result 200 rows (10 times 20).
La juntura cruzada entre dos tablas proporciona todas las combinaciones posibles de renglones entre las dos tablas. Por ejemplo, si se tienen 10 renglones en una tabla y 20 en la otra, el resultado serán 200 reglones (10 por 20).

Problem 1
city_bank > Test the following SELECT command which is a cross join.
Pruebe el siguiente comando SELECT el cual es una juntura cruzada.

SQL
SELECT name, account_id
FROM client, client_account;

cross_join

Tip
Always use a WHERE clause in a multi-table join unless you really need to use this type of query.
Siempre use el comando WHERE cuando realice una consulta de la juntura de varias tablas, a menos que en verdad requiera hacer ésto.

Tip
If you ran a cross join query against a production database, many people would be angry with you because it would take a long time to run. Chances are, your DBA would probably kill the query and have a long chat with you in the process.
Si usted ejecuta una consulta con juntura cruzada en una base de datos en producción, mucha gente se enojará con usted porque la consulta puede tomar un gran tiempo para ejecutarse. Seguramente, el administrador de la base de datos terminará la consulta y tendrá una larga plática con usted mientras tanto.

Tip
To build a relation from two tables over a compatible attribute from each table WHERE must be used. This means that only those rows where the compatible attributes have the same values will be returned. The relationship between the two tables is important when you decide on joining two tables.
Para construir una relación entre dos tablas por medio de un atributo compatible de cada tabla se debe usar el comando WHERE. En otras palabras, solamente se regresan los renglones para los cuales los atributos compatibles tienen el mismo valor. La relación entre dos tablas es muy importante cuando se realiza una consulta del tipo juntura.

Tip
A column may appear twice in a joint, reflecting the fact that a column by that name exists in two tables. If we wished to display this column one, we need to qualify the column specification with a table reference. We need to do this whenever column names appear in more than one table. Without the table reference, the column reference becomes ambiguous.
Una columna puede aparecer dos veces en una juntura, reflejando el hecho de que una columna con el mismo nombre aparece en dos tablas. Si se desea mostrar solamente una columna, se debe especificar de cual tabla se desea mostrar esta columna. Sin indicar de cual tabla se hace referencia, el comando se vuelve ambiguo y seguramente no podrá ser ejecutado.

Equi Join

An equi-join between two tables is a join based on an exact match between an attribute in both tables. The WHERE clause provides the search conditions that specifies the match of the columns between the tables.
Se consigue cuando la juntura de dos tablas se basa entre la coincidencia entre dos atributos en ambas tablas usando el símbolo '='. El comando WHERE proporciona las condiciones de búsqueda que especifican la coincidencia entre las dos tablas.

Parent/Child Relationship

In a parent/child relationship, the primary key and foreign key in the tables create the relationship. The table within the foreign key is the child in the relationship, and the table with the primary key is the parent.
En este tipo de relación, la llave primaria y la llave extranjera crean la relación entre las tablas. La tabla con la llave extranjera es la tabla hijo de la relación, y la tabla con la llave primaria es el padre.

Problem 2
city_bank > Test the following SELECT command which is a cross join.
Pruebe el siguiente comando SELECT el cual es una juntura cruzada.

SQL
SELECT name, account_id
FROM client, client_account
WHERE client_account.client_id =client.client_id;

city_bank_join

cb_clientacc

Tip
When writing queries using multiple tables, it is convenient to use aliases to abbreviate the table references as shown in the following problem.
Cuando se escriben consultas que operan sobre varias tablas, es conveniente usar aliases para abreviar las referencias a las tablas como se muestra en el siguiente ejemplo.

Problem 3
city_bank > Test the following SELECT command which is a cross join. In this case, the client table has the alias c, and the client_account has the alias ca. Any aliases can be used; however try to use short aliases that help you remember the name of the table.
Pruebe el siguiente comando SELECT el cual es una juntura cruzada. En este caso, la tabla client tiene el alias c, y la tabla client_account tiene el alias ca. Cualquier alias puede ser usado; sin embargo trate de usar aliases cortos que le ayuden a recordar el nombre de la tabla.

SQL
SELECT c.name, ca.client_id, ca.account_id
FROM client c, client_account ca
WHERE ca.client_id =c.client_id

city_bank_link

cb_alias

Equi Join Steps

  1. Open the database diagram
  2. Identify which tables contain the required information
  3. Identify linking tables that connect the tables where the required information is
  4. Write the FROM part of the query assigning aliases to each table
  5. Write the SELECT part of the query choosing the required columns from each table
  6. Write the WHERE part of the query using the references (linking arrows in the diagram) of the tables

  1. Abra el diagrama de la base de datos
  2. Identifique cuales tablas contienen la información requerida
  3. Identifique las tablas conectoras que enlazan las tablas dónde está la información requerida
  4. Escriba la parte FROM de la consulta asignando nombres cortos a cada tabla
  5. Escriba la parte SELECT de la consulta escogiendo las columnas requeridas de cada tabla
  6. Escriba la parte WHERE de la consulta usando las referencias de las tablas (flechas de enlace en el diagrama)

Non-Equi Join

A non-equi-join uses the comparison operators: >, <, and <>. Non-equi-joins can serve a practical use for decision support queries, however, when there's a need to compare and contrast data.
Es aquella en la que la juntura se usan los operadores de comparación: >, <, y <>. Su uso se reserva cuando se desea comparar y contrastar resultados.

Problem 4
city_bank > Test the following SELECT command which is a cross join. In the query, the client table was joined with the client_account table using the client_id (which has to be same value in both tables). The result, then, was joined with the account table using the attribute account_id.
Pruebe el siguiente comando SELECT el cual es una juntura cruzada. En la consulta, se juntaron los renglones de la tabla client con aquellos renglones en la tabla client_account que tienen el mismo client_id. El resultado fue entonces juntado con la tabla account usando el atributo account_id.

SQL
SELECT c.client_id, a.account_id, balance, name
FROM client c, client_account ca, account a
WHERE ca.account_id=a.account_id
AND c.client_id=ca.client_id

city_bank_three

cb_three

Tip
In the FROM part of a SELECT command, only the tables from where the information is extracted must be included. If these tables are connected by a linking table, then the linking table must also be included. Observe that if there are four tables included in FROM, then there must be at least three equal-statements included in WHERE.
En la parte FROM de un comando SELECT se deben incluir solamente las tablas de donde se extraerán los datos. Si estas tablas están enlazadas por medio de una tabla de conexión también será necesario incluir estas tablas de conexión. Observe que si hay cuatro tablas incluidas en FROM, entonces debe haber al menos tres igualaciones incluidas en la parte WHERE.

Problem 5
city_bank > Write a query to display the name of the client, account_id and balance for those clients whose balance is bigger than 100 dollars.
Escribir una consulta SQL para mostrar el nombre de todos los clientes, con sus números de cuenta para aquellos clientes que tienen un balance mayor a 100 dólares.

cb_balance

Problem 6
motorola > Write a query to display the name of the employees who works for a department that has a budget of more than 5,000.00 dollars.
Escribir una consulta SQL para mostrar el nombre de los empleados que trabajan para el departamento que tiene un presupuesto mayor a 5000.00 dólares.

mot_budget

Problem 7
motorola > Write a query to display the name of the employees who speak French.
Escribir una consulta SQL para mostrar el nombre de los empleados que hablan francés.

mot_french

Problem 8
motorola > Write a query to display the name of the departments that have employees who know how to speak German.
Escribir una consulta SQL para mostrar el nombre de los departamentos que tienen empleados que hablan alemán.

mot_german

Self-Join

Sometimes it is necessary to have a multiple-table query that has a relationship with itself. The only way to accomplish this is by doing a self-join for the table in question.
Algunas veces se tienen consultas de una tabla que tienen relaciones con sí misma. La única forma de lograr esto es por medio de una auto-juntura con la tabla.

Problem 9
city_bank > We wish to find which accounts are shared by two clients. Write the SQL statement to get the output shown. DIFFICULT.
Se desea encontrar cuales cuentas son compartidas por dos clientes. Escriba el comando SQL para conseguir la salida mostrada. DIFICIL.

cb_sameacc

Problem 10
city_bank > We wish to find which accounts are shared by two clients. Write a SQL statement to show the names of these clients. DIFFICULT.
Se desea descubrir cuales cuentas son compartidas por dos clientes. Escriba el comando SQL para mostrar los nombres de estos clientes. DIFICIL.

cb_accname

Problem 11
motorola > Modify the motorola.sql file so that the script creates and populates the table employee_su shown below. First, create the table without the references. Second, insert the employees. Finally, add the reference using the command ALTER as shown below.
Modifique el archivo motorola.sql para que el script cree y llene la tabla employee_su que se muestra debajo. Primero, cree la tabla sin las referencias. Segundo, inserte los empleados. Finalmente, agregue la referencia usando el comando ALTER como se muestra debajo.

employee_su

motorola.sql
CREATE TABLE employee_su
(
     ...
) ;
GO

INSERT INTO employee_su VALUES(1, 'Lacombe, Teresa', 'Sales', 2);
...
GO

ALTER TABLE employee_su ADD FOREIGN KEY(supervisor_id) REFERENCES employee_su(emp_id);
GO

Problem 12
motorola> There is a Supervisor column in the employee_su table. Write the SQL statement to get the output shown.
Hay una columna llamada Supervisor en la tabla employee_su. Escriba un comando SQL para conseguir la salida mostrada.

mot_supervisor

Problem 13
kimberly > Write the kimberly.sql file to create an populate the kimberly database. Using: (a) Microsoft SQL Server, (b) Oracle, (c) MySQL.
Escriba el archivo kimberly.sql para crear y llenar la base de datos kimberly. Usando: (a) Microsoft SQL Server, (b) Oracle, (c) MySQL.

© Copyright 2000-2021 Wintempla selo. All Rights Reserved. Jul 22 2021. Home