I'm doing a query to get all the clientes
and total de cuentas asociadas
but I don't want to show the ones that I already have associated.
I have the following tables:
----dbClientes----- --------syUsers-------- -----syUsers_WebAccess----
| id | Nombre | | id | Nombre | | id | idUser | idClient |
------------------- ----------------------- --------------------------
| 1 | Juan | | 1 | Contabilidad | | 1 | 1 | 1 |
| 2 | Victor | | 2 | JuankGlezz | | 2 | 1 | 3 |
| 3 | Arturo | ----------------------- | 3 | 2 | 1 |
------------------- --------------------------
Doing the following query brings me all the clientes
with the total de cuentas asociadas
.
SELECT DISTINCT C.Nombre, C.id, IFNULL(NC.NumCuentas,0) AS NumCuentas
FROM dbclientes C
LEFT JOIN (
SELECT idClient, count(id) AS NumCuentas FROM syUsers_WebAccess
) NC ON NC.idCliente = C.id
It gives me as a result:
Nombre idCliente NumCuentas
Juan 1 2
Victor 2 1
Arturo 3 0
Now I want to apply Get all clientes
Except those clientes
associated with it JuankGlezz
, that is, I expect this as a result:
Nombre idCliente NumCuentas
Victor 2 1
Arturo 3 0
In case the selected user Contabilidad
was the following would be displayed:
Nombre idCliente NumCuentas
Victor 2 1
How would the query be to obtain those results? , try this, but it only works if there is only one associated account.
SELECT * FROM (
SELECT DISTINCT C.Nombre, C.id, IFNULL(NC.NumCuentas,0) AS NumCuentas
FROM dbclientes C
LEFT JOIN (
SELECT idCliente, count(id) AS NumCuentas FROM syUsers_WebAccess
) NC ON NC.idCliente = C.id
) TB
WHERE id != (SELECT idCliente FROM syUsers_WebAccess WHERE idUser = 48)
Note: I can't just put the
idClient
, because from the application I get only theidUser
The simplest for this is to use
NOT EXISTS
:Here is a demo of this.
Another solution is to do a
LEFT JOIN
to tablesysUsers_WebAcces
and exclude allclientes
where theidUser = 2
For example:
Demo
PS : You could replace the one
NOT IN
with the one in @Lamak'sNOT EXISTS
answer