Select non-empty field

Asked

Viewed 266 times

1

demo table

 id  imagem       flash       codigo
 1   fda.jpg
 2             asdfasd.sfw
 3                           adsense

is there any way to SELECT only the non-empty? if yes what is the best way in PHP or SQL?

          $sql = "SELECT * FROM publicidade ORDER BY RAND() LIMIT 6";

         if flash,image = "" echo codgio

         if codigo,image = "" echo flash

is around or has some way more proper?

  • 1

    Empty values are empty strings or NULL?

  • Are Empty Strings

1 answer

3


You can use the expression CASE in select, for example:

SELECT
  CASE
    WHEN imagem != '' THEN imagem
    WHEN flash != '' THEN flash
    WHEN codigo != '' THEN codigo
    ELSE NULL
  END AS val
FROM publicidade
ORDER BY RAND()
LIMIT 6

And in php, with the result of this query you can use:

echo $row['val'];
  • really worked but now that I saw it here has to be via php even because the call codes are different for each type I’ll see if the case of php works the same way

  • 1

    Try to use a better template in the database. The correct one would be to have a column of the value type, not a column for each type. For example, tipo_publicidade => "imagem", valor_publicidade => "fda.jpg". That way you would only need to check the type of the value, nor would you need this query that I wrote as an answer. If you want I’ll explain it to you somewhere else.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.