SQL Query - unexpected CASE token

I have the following SQL query:

 SELECT w.id, w.name, m.subject, m.id FROM users AS w, i_c AS c, (SELECT _id, u_id, subject FROM i_m WHERE (_id, tmstmp) IN (SELECT _id, max(tmstmp) FROM i_m GROUP BY _id)) m WHERE (c.uid_1 = '2' OR c.uid_2 = '2') AND CASE WHEN c.uid_1 = '2' THEN w.id = c.uid_2 WHEN c.uid_2 = '2' THEN w.id = c.uid_1 END AND (c.id = m.id) ORDER BY m.tmstmp DESC 

It works fine on my first server, but on the second server it gives me

 Unexpected Token. (near "c" at position 280) 

I looked at some of these problems, but still could not find a solution. It seems the problem is this: CASE .

Can anyone help me? Any help is appreciated. Thanks in advance.

+5
source share
1 answer

You CASE are incorrect, CASE is an expression, not an operator, you can specify only the value THEN , not a condition.

Change it like this:

  w.id = CASE WHEN c.uid_1 = '2' THEN c.uid_2 WHEN c.uid_2 = '2' THEN c.uid_1 END 

Like @Jarlh, you can use OR , which can improve the query a bit:

 WHERE ((c.uid_1 = '2' AND w.id = c.uid_2) OR (c.uid_2 = '2' AND w.id = c.uid_1)) AND 
+3
source

All Articles