Let's see if I explain it to you with code.
In a query that collects several tables, if you want to bring columns that do not have data in any of the matches, you can use LEFT JOIN
.
One of the things that happens when you use LEFT JOIN
is the following:
If there is a row in A
that matches the WHERE
clause, but there is no
no row in B
that matches condition ON
, a row is generated
B
additional with all columns set to NULL
.
For more details, see the MySQL documentation .
In the following code, suppose that your table A
is a table of personas
and your table B
is a table of ciudades
and you want to show the cities of birth of each person , while still showing those that do not have any city of birth indicated, the query would be something like this:
Consulta
SELECT
p.persona_nom,
c.ciudad_nom
FROM persona p
LEFT JOIN ciudad c
ON p.ciudad_id=c.ciudad_id;
Resultado
persona_nom ciudad_nom
1 Pedro Galilea
2 Santiago Betsaida
3 Juan Patmos
4 María Magdala
5 Sin Ciudad NULL
Ejemplo completo:
ver demo
/*
-- ATENCIÓN NO USE DROP TABLE CON SUS TABLAS REALES
-- YA QUE DROP TABLE BORRARÁ SUS DATOS
-- DROP TABLE SE USA AQUÍ SÓLO PARA PODER PROBAR LOS DATOS */
DROP TABLE IF EXISTS ciudad;
DROP TABLE IF EXISTS persona;
/* NO COPIE LA SENTENCIA ^ DROP TABLE ^ EN SUS DATOS REALES */
CREATE TABLE IF NOT EXISTS persona
('persona_id' serial,
'persona_nom' varchar(50),
'ciudad_id' int
);
INSERT INTO persona
('persona_nom', 'ciudad_id')
VALUES
('Pedro', 1),
('Santiago', 2),
('Juan', 3),
('María',4),
('Sin Ciudad',NULL)
;
CREATE TABLE ciudad
('ciudad_id' int,
'ciudad_nom' varchar(50)
);
INSERT INTO ciudad
('ciudad_id', 'ciudad_nom')
VALUES
(1, 'Galilea'),
(2, 'Betsaida'),
(3, 'Patmos'),
(4, 'Magdala')
;
-- CONSULTA
SELECT
p.persona_nom,
c.ciudad_nom
FROM persona p
LEFT JOIN ciudad c
ON p.ciudad_id=c.ciudad_id;