Search code examples
mysqlselectsql-likeconcatenation

MySql Select 2 tables Like


I have this query but apparently it can loop and crash the server.

SELECT neveras.Panel, contactos.Email FROM neveras, contactos
WHERE neveras.Alarma = 1 And  Estado <> 1
And contactos.Sensor 
LIKE CONCAT('%,',(Select Usuario FROM neveras where Alarma = 1),',%')

Table neveras:

Id|Panel|Usuario|Alarma|Estado
 1  uno     1       1     2
 2  dos     1       2     1
 3  tres    2       2     1
 4  cuatro  2       2     1
 5  cinco   3       2     1

Table Contactos:

Id  |Email   |Nombre    |Sensor
 1  uno@uno   nombre1     1,3,5   
 2  dos@dos   nombre2     2,4    

This table has this structure to avoid repeating values

I appreciate your help.


Solution

  • This is a bit of a guess as I am not 100% sure what you are trying to achieve, but give this a try -

    SELECT neveras.Panel, contactos.Email 
    FROM neveras
    INNER JOIN contactos
        ON FIND_IN_SET(neveras.Usuario, contactos.Sensor)
    WHERE neveras.Alarma = 1
    AND neveras.Estado <> 1
    

    As Mosty pointed out it would definitely help if you posted an example of what you expect in the result.

    Further to that, you should move the multiple values in your Sensor field to a many-to-many table (contactos_id, sensor_id). There is no way for the optimizer to do anything clever with your comma sparated list so any filtering or joining on that field will be very inefficient.