Search code examples
mysqlif-statementnestedgroup-concat

How can I use nested cases in mySQL?


I want to work with nested cases:

SELECT *, 
    GROUP_CONCAT(DISTINCT CONCAT(
    CASE
      WHEN data.name NOT "field" THEN   
        CASE
          WHEN data.category = "A" THEN "A"
          WHEN data.category = "B" THEN "B"
          ELSE "C"
        END,data.name
    END
   )ORDER BY FIND_IN_SET(data.category,"B,C,A") ASC, data.name ASC SEPARATOR " <br>") AS result
  FROM data;');

But I get an error message:

Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'data.name END ' at line 11


Solution

  • You have some syntax error in your query. Run the following code in your query editor, and it will be ok.

    SELECT 
     *,
    GROUP_CONCAT(
    DISTINCT CONCAT(
      CASE
        WHEN data.name = "field" 
        THEN (
          CASE
            WHEN data.category = "A" 
            THEN "A" 
            WHEN data.category = "B" 
            THEN "B" 
            ELSE "C" 
          END
        ) 
      END,
        data.name
    ) 
    ORDER BY FIND_IN_SET(data.category, "B,C,A") ASC,
    data.name ASC SEPARATOR " <br>"
    ) AS result 
     FROM DATA;