I don’t know about Mysql, but in SQL Server it is possible to write in 3 different ways:
NOT IN
SELECT usuarios.*
FROM usuarios
WHERE id NOT IN(
SELECT IdUsuario
FROM cartao
)
NOT EXISTS
SELECT usuarios.*
FROM usuarios
WHERE id NOT EXISTS(
SELECT IdUsuario
FROM cartao
)
LEFT JOIN combined with IS NULL
SELECT usuarios.*
FROM usuarios
LEFT JOIN cartao ON usuarios.id = cartao.IdUsuario
WHERE cartao.IdUsuario IS NULL
again, I don’t know about Mysql, but in SQL Server, the alternatives NOT IN
and NOT EXISTS
perform better than LEFT JOIN
.
It is also worth remembering that this result (better or worse) will also depend on the version of the Bank Engine, which can be slow in an old version, can be fast in a more current version.
In the link below there is a detail (SQL Server
) about the statement I made above (in any case you should make your own tests using your environment):
NOT IN vs. NOT EXISTS vs. LEFT JOIN / IS NULL: SQL Server
without using a subconsulta, it would have as?
– lelopes
@Lelopes I don’t know, may exist.
– rray