No unirse a mesas dependiendo de las condiciones.

Resuelto elizabeth asked hace 8 meses • 3 respuestas

Por ejemplo, tengo dos mesas.

mesa un

id

1
2
3
4
5

tabla b

id  type
1   type1
2   type2
3   type3
4   type1
5   type1
1   type1
2   type1
5   type2

Me uno a mis mesas.

select a.id, b.type from 
table a left join table b on
a.id = b. id

para id = 5 obtengo:

id    type 
5     type1
5     type2

solo necesito el id donde escribe 1

select a.id, b.type from 
table a left join table b on
a.id = b. id where b.type = 'type1'

para id = 5 obtengo:

id    type 
5     type1

id =5 también tiene tipo2 en la tabla 2.

Mi problema es que necesito excluir el valor de identificación donde hay al menos un valor de tipo 2 en el campo de estadísticas.

Para id = 5 espero la tabla vacía. Porque id =5 también tiene tipo2

¿Es posible darse cuenta de esto? Intenté usar existe, contiene, pero sin resultado.

elizabeth avatar Feb 16 '24 19:02 elizabeth
Aceptado

Podemos usar la lógica existente:

SELECT a.id, b.type
FROM tableA a
LEFT JOIN tableB b
    ON a.id = b.id
WHERE
    b.type = 'type1' AND
    NOT EXISTS (
        SELECT 1
        FROM tableB t
        WHERE t.id = b.id AND
              t.type = 'type2'
    );
Tim Biegeleisen avatar Feb 16 '2024 12:02 Tim Biegeleisen

Esto será útil para lograr el resultado deseado.

SELECT *
    FROM Table1 t1
    LEFT JOIN Table2 t2 ON t1.id = t2.id
    WHERE NOT EXISTS (
        SELECT 1
        FROM Table1
        WHERE id = t1.id AND type = 'type2'
    );
Muteeb ali avatar Feb 16 '2024 12:02 Muteeb ali