SQL查询 - CASE意外令牌

时间:2016-06-28 09:04:26

标签: mysql sql case

我有以下SQL查询:

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

它在我的第一台服务器上工作正常但在第二台服务器上却给了我

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

看了一些类似的问题,但仍未找到解决方案。 似乎问题是CASE

有人能帮帮我吗?任何帮助将非常感激。提前谢谢。

1 个答案:

答案 0 :(得分:3)

CASE错了,CASE是表达式,而不是语句,您只能在THEN中指定一个值,而不是条件。

将其更改为:

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

与@Jarlh建议一样,您可以使用OR来更好地优化查询:

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