How to compare two rows of different tables and get records that meet condition, if not, show null MySQL?

1

I have two tables with the same fields, but each user inserts different records (there is a range of 78 possible records that each user can insert in their table) what I want to be able to do is obtain in which fields the records are similar and in which are not (since there is a possibility that the records inserted in the tables of the 2 users are similar or not)

I want to obtain a row that shows in which fields the records of the two tables of the two users are equal, when they are equal to show the same records and when not, only show a NULL .

I tried this in MySQL 5.7 :

SELECT * FROM TablaA as A
FULL OUTER JOIN TablaB as B
ON (A.Col1 = B.Col1 and A.Col2 = B.Col2)
    
asked by gabo luna 26.06.2017 в 20:08
source

1 answer

0

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;
    
answered by 27.06.2017 / 00:02
source