-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmodulo-07.sql
More file actions
97 lines (72 loc) · 2.39 KB
/
modulo-07.sql
File metadata and controls
97 lines (72 loc) · 2.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
-- Conteo de registros de nuestras tablas
SELECT count(*) FROM invoices;
SELECT count(*) FROM invoice_items;
-- CROSS JOIN sin usar la clausula JOIN
SELECT *
FROM invoices, invoice_items;
-- CROSS JOIN utilizando la clausula JOIN
SELECT *
FROM invoice_items CROSS JOIN invoices;
-- NATURAL JOIN
-- Filtra la relación de la tabla A con la tabla B con el nombre del campo idéntico.
CREATE TABLE alpha (
id INT NOT NULL,
description VARCHAR(50) NOT NULL,
CONSTRAINT alpha_id_pk PRIMARY KEY (id)
);
CREATE TABLE beta (
id INT NOT NULL,
title VARCHAR(50) NOT NULL,
CONSTRAINT beta_id_fk FOREIGN KEY (id)
REFERENCES alpha (id)
ON UPDATE RESTRICT
ON DELETE RESTRICT
);
CREATE TABLE gama (
id INT NOT NULL,
description VARCHAR(50) NOT NULL,
CONSTRAINT gama_id_pk PRIMARY KEY (id)
);
-- Poblado de información
INSERT INTO alpha VALUES (1, 'UNO'), (2, 'DOS'), (3, 'TRES'), (4, 'CUATRO');
INSERT INTO beta VALUES (1, 'ONE'), (2, 'TWO'), (3, 'THREE');
INSERT INTO gama VALUES (1, 'ONE'), (2, 'TWO'), (3, 'THREE');
SELECT * FROM alpha CROSS JOIN beta;
SELECT * FROM alpha NATURAL JOIN beta;
SELECT * FROM alpha NATURAL JOIN gama;
-- INNER JOIN
SELECT * FROM persons;
SELECT * FROM invoices;
-- Encabezado de facturas
SELECT persons.id, persons.first_name, persons.last_name,
persons.birthday, invoices.invoice_date
FROM persons INNER JOIN invoices
ON persons.id = invoices.person_id;
-- Detalle de facturas
SELECT persons.id, persons.first_name, persons.last_name,
persons.birthday, invoices.invoice_date,
products.product_name, invoice_items.price,
invoice_items.quantity,
(invoice_items.price * invoice_items.quantity) AS total_price
FROM persons INNER JOIN invoices
ON persons.id = invoices.person_id
INNER JOIN invoice_items
ON invoices.id = invoice_items.invoice_id
INNER JOIN products
ON products.id = invoice_items.product_id;
-- LEFT JOIN
-- Mostrar todos nuestros usuarios así no hayan comprado.
SELECT first_name, last_name, invoice_date
FROM persons LEFT JOIN invoices
ON persons.id = invoices.person_id;
-- RIGHT JOIN
SELECT first_name, last_name, invoice_date
FROM invoices RIGHT JOIN persons
ON persons.id = invoices.person_id;
-- FULL JOIN
INSERT INTO gama VALUES (5, 'FIVE'), (6, 'SIX');
SELECT * FROM alpha;
SELECT * FROM gama;
SELECT *
FROM alpha FULL JOIN gama
ON alpha.id = gama.id;