Problems joining two sql tables and comparing if there is

1

I want to get a query where Cve, Name and Exist, in one table I have the catalago and in another I have the ones that exist, therefore I want to get all the catalago but with an extra field that is in 1 those that exist and in 0 those that are

**tabla catalago:**CAMPOS
cve_ventana|nombre

**tabla roles** CAMPOS
fk_cve_Ventana

**NECESITO GENERAR ESTO:**

Cve_Ventana | Nombre | Existe
1           |carro   |1      | <- que si existe en la tabla roles 
2           |llantas |0      |<- no esta en la tabla roles

Quiero obtener todos los registro de la tabla T_Ventanas y los registros que no estén en T_Roles me los marque como "0" en Existe
 
    
asked by 23.06.2018 в 20:23
source

2 answers

2

I think the type of union you need here is a LEFT JOIN , which will give you NULL in the mismatches. Based on that same value, you can use CASE WHEN to show 1 or 0 evaluating some column of the table you will join with LEFT JOIN .

To group it or not I leave it to your criteria, and it would be necessary only in the case that there are several rows with the same id in the foreign table.

The query would be like this:

a With SQL Server

You can see a COMPLETE DEMO IN REXTESTER , operating on real data.

SELECT 
    c.cve_ventana, 
    c.nombre, 
    CASE WHEN r.fk_cve_Ventana IS NULL THEN 0 ELSE 1 END 'Existe' 
FROM catalogo c 
LEFT JOIN roles r
ON c.cve_ventana = r.fk_cve_Ventana;

b. With MySQL

You can see a COMPLETE DEMO IN REXTESTER , operating on real data.

In MySQL you can use IF , as follows:

SELECT 
    c.cve_ventana, 
    c.nombre, 
    IF(r.fk_cve_Ventana,'1','0') Existe 
FROM catalogo c 
LEFT JOIN roles r
ON c.cve_ventana = r.fk_cve_Ventana;

In a. as in b. the result would be:

Cve_Ventana | Nombre | Existe|
1           |carro   |1      | 
2           |llantas |0      |
    
answered by 24.06.2018 в 16:13
0

You can do it in MySQL with one condition, if it exists it is 1 and if not 0.

SELECT c.* ,
IF (fk_cve_ventana = cve_ventana,1,0) AS existe
FROM catalogo c 
JOIN roles r ON r.fk_cve_ventana=c.cve_ventana
GROUP BY c.cve_ventana
    
answered by 23.06.2018 в 22:50