Case mysql error

2
SELECT count(*),
CASE count(*)
WHEN >=0 
then Esta vacio
end
FROM producto

By putting this query I get the error

#1064 - Algo está equivocado en su sintax

I have been reading online and I can not find the solution to this problem

    
asked by bsg 26.04.2017 в 11:16
source

2 answers

4

The CASE syntax that you are trying to use is:

CASE case_value
    WHEN when_value THEN statement_list
    [WHEN when_value THEN statement_list] ...
    [ELSE statement_list]
END CASE

We can differentiate two problems in your SQL query:

  • Characters must be delimited correctly (text Está vacío must be enclosed in single quotes).
  • The CASE syntax you want to use does not allow >=0 as a value of when_value .

You could have used a complete check ( count(*)>=0 ) but its result would have been compared ( TRUE is 1 and FALSE is 0) with case_value , causing unexpected results ( count(*)>=0 ALWAYS is worth TRUE because it will always be equal to or greater than 0), so it would always come out Está vacío as a result.

PROPOSED SOLUTION:

If you want to get a list keeping the number of records found in count(*) and add the text Está vacío only in those that have 0, then you can do:

SELECT
  campo,
  CASE count(*)
    WHEN 0 THEN 'Está vacío'
    ELSE count(*)
  END CASE numero
FROM
  producto
GROUP BY
  campo

The SELECT works as always, the first campo could be (optionally) the field by which you make the GROUP BY of products (*).

The second field would be, depending on the value of count(*) the character string Está vacío if the account is 0 or count(*) otherwise. The name of the field will be called numero .

FULLEST EXAMPLE:

This example completes the content of the numero field including plural and singular distinction.

SELECT
  campo,
  CASE count(*)
    WHEN 0 THEN 'Está vacío'
    WHEN 1 THEN 'Hay 1 producto'
    ELSE CONCAT('Hay ', count(*), ' productos')
  END CASE numero
FROM
  producto
GROUP BY
  campo

(*) If you do not want to use, or do not use, a GROUP BY in your query, then you can remove both the field in SELECT and the clause GROUP BY :

SELECT
  CASE count(*)
    WHEN 0 THEN 'Está vacío'
    ELSE count(*)
  END CASE numero
FROM
  producto
    
answered by 26.04.2017 / 12:17
source
3

The CASE syntax could be moving count(*) behind when

You also need to surround the text in quotes ' (thanks Oscar)

SELECT 
    count(*),
CASE 
    WHEN count(*) = 0  THEN 'está vacio' END 
FROM 
    producto
    
answered by 26.04.2017 в 11:43