MySQL seleccionar donde la columna no está vacía


En MySQL, ¿puedo seleccionar columnas solo donde existe algo?

Por ejemplo, tengo la siguiente consulta:

select phone, phone2
from jewishyellow.users
where phone like '813%'
and phone2

Estoy tratando de seleccionar solo las filas donde el teléfono comienza con 813 y phone2 tiene algo en él.

 146
Author: Eric Leschinski, 2009-12-08

10 answers

Compare el valor de phone2 con una cadena vacía:

select phone, phone2 
from jewishyellow.users 
where phone like '813%' and phone2<>''

Tenga en cuenta que el valor NULL se interpreta como false.

 224
Author: Ivan Nevostruev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-07-16 02:39:38

Para comprobar si el campo es NULO use IS NULL, IS NOT NULL operadores.

Referencia MySQL http://dev.mysql.com/doc/refman/5.0/en/working-with-null.html

 41
Author: Stanislav Stoyanov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-12-08 19:32:44

Compruebe NULL y valores de cadena vacíos:

select phone
, phone2 
from users 
where phone like '813%' 
and trim(coalesce(phone2, '')) <>''

N.B. Creo que COALESCE() es SQL standard(-ish), mientras que ISNULL() no lo es.

 30
Author: davek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-12-08 19:40:50

Si hay espacios en el campo phone2 de entrada de datos inadvertant, puede ignorar esos registros con las funciones IFNULL y TRIM:

SELECT phone, phone2
FROM jewishyellow.users
WHERE phone LIKE '813%'
    AND TRIM(IFNULL(phone2,'')) <> '';
 15
Author: micahwittman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-12-08 19:34:10

Una respuesta que he estado usando que ha estado funcionando para mí bastante bien que no he visto ya aquí (esta pregunta es muy antigua, por lo que puede que no haya funcionado entonces) es en realidad

SELECT t.phone, 
       t.phone2 
  FROM jewishyellow.users t
 WHERE t.phone LIKE '813%' 
   AND t.phone2 > ''

Observe la parte > '', que comprobará si el valor no es null, y si el valor no es solo espacio en blanco o en blanco.

Básicamente, si el campo tiene algo en él que no sea espacio en blanco o NULL, es verdadero. También es súper corto, por lo que es fácil de escribir, y otra ventaja sobre el COALESCE() y IFNULL() funciones es que esto es amigable índice, ya que no está comparando la salida de una función en un campo a nada.

Casos de prueba:

SELECT if(NULL > '','true','false');-- false
SELECT if('' > '','true','false');-- false
SELECT if(' ' > '','true','false');-- false
SELECT if('\n' > '','true','false');-- false
SELECT if('\t' > '','true','false');-- false
SELECT if('Yeet' > '','true','false');-- true

UPDATE Hay una advertencia a esto que no esperaba, pero los valores numéricos que son cero o inferiores son no mayores que una cadena en blanco, por lo que si estás tratando con números que pueden ser cero o negativos que NO HAGAS ESTO, me mordió muy recientemente y fue muy difícil de depurar: (

 9
Author: Brian Leishman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-10 12:52:38
select phone, phone2 from jewishyellow.users 
where phone like '813%' and phone2 is not null
 8
Author: Klaus Byskov Pedersen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-12-08 19:43:50
SELECT phone, phone2 
FROM jewishyellow.users 
WHERE phone like '813%' and (phone2 <> "");

Puede necesitar algunos ajustes dependiendo de cuál sea su valor predeterminado. Si permites el relleno nulo, entonces puedes hacer "Not NULL" en su lugar, lo cual obviamente es mejor.

 4
Author: Satanicpuppy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-12-08 22:11:21

Podemos usar CASE para establecer un valor en blanco a algún char o Cadena. Estoy usando NA como cadena predeterminada.

SELECT phone,   
CASE WHEN phone2 = '' THEN 'NA' END AS phone2 ELSE ISNULL(phone2,0) 
FROM jewishyellow.users  WHERE phone LIKE '813%'
 2
Author: Atul,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-29 04:42:56

Uso:

SELECT t.phone, 
       t.phone2 
  FROM jewishyellow.users t
 WHERE t.phone LIKE '813%' 
   AND t.phone2 IS NOT NULL
 1
Author: OMG Ponies,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-12-08 19:34:40

Puede usar comodín de operador como para lograr esto:

SELECT t.phone, 
       t.phone2 
FROM jewishyellow.users t
WHERE t.phone LIKE '813%' 
  AND t.phone2 like '[0-9]';

De esta manera, puede obtener todos los teléfonos 2 que tienen un prefijo numérico.

 0
Author: Panda,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-16 03:41:39