Question

I currently have a problem with the multiple when into case. When I remove the second when, it works. What is wrong with it?

The reported MYSQL error is:

#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 'as param2 on param2.param_micro_site=i1.i_micro_site else null END )' at line 1

I tried these suggestions:

MySQL - Combining multiple WHEN conditions in CASE

How to write a MYSQL CASE WHEN statement with multiple search conditions?

But it didn't solved my problem.

SELECT * FROM items i1
join param on 
(
case 
    when (ITEM_ID=param_item_id and i_status=1 and item_page=164) 
    then param_item_id=ITEM_ID 
    when (i_micro_site>=1 and i_status=7 and (EXISTS(select * from multiple where multiple_id=ITEM_ID and multiple_cat=21 and multiple_enum="item") || item_page=169)) 
    then (SELECT * from items i2 join pages on i2.item_page=p_ID and p_cat in (21,29,0) join param where param_micro_site=i1.i_micro_site and param_item_id in(i1.ITEM_ID,i2.ITEM_ID)) as param2 on param2.param_micro_site=i1.i_micro_site 
else null END 
)

Thank you

Was it helpful?

Solution

Below is an attempt to format your query in a somewhat readable way:

SELECT *
FROM items i1 join
     param
     on (case when (ITEM_ID=param_item_id and i_status=1 and item_page=164) 
              then param_item_id=ITEM_ID 
              when (i_micro_site>=1 and i_status=7 and
                    (EXISTS(select *
                            from multiple
                            where multiple_id=ITEM_ID and multiple_cat=21 and multiple_enum="item"
                           ) || item_page=169
                    )
                   ) 
              then (SELECT *
                    from items i2 join
                         pages on i2.item_page=p_ID and p_cat in (21,29,0) join
                         param
                    where param_micro_site=i1.i_micro_site and
                          param_item_id in(i1.ITEM_ID,i2.ITEM_ID)
                   ) as param2
on param2.param_micro_site=i1.i_micro_site 
else null END 
)

Here are observations up to the on after param2:

  • The subquery for the then clause is finished.
  • A subquery in a then clause cannot take a column (or table) alias.
  • The subquery is returning more than one column. Even if all tables in the subquery had only one column, the * would bring back more than one.

Apart from the syntax, this query is just entirely unreadable. I would suggest that you ask another question, provide table layouts, sample data, and desired results. Someone can probably figure out a better way to write the query that you have attempted.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top