SQL-在“ AND”之后使用“ CASE”

时间:2018-10-23 18:36:20

标签: sql

我有以下SQL查询:

SELECT 
    ts.id, t.id, t.name
FROM 
    table1 ts
INNER JOIN 
    tabble2 t ON ts.ta = t.ta
              AND CASE 
                     WHEN :var1 = 0 THEN ts.id = :var1
                     ELSE ts.id = :var1 AND ts.em = :var2
                  END
ORDER BY  
    ts.id DESC;

var1var2是我从代码传递的变量。

该查询是否有问题?由于某些原因,它似乎无法提供正确的结果。

2 个答案:

答案 0 :(得分:3)

SELECT ts.id, t.id, t.name
FROM table1 ts
INNER JOIN tabble2 t 
   ON ts.ta = t.ta
   AND ((:var1 = 0 AND ts.id = :var1) OR (:var1 <> 0 AND ts.id = :var1 AND ts.em = :var2))
ORDER BY ts.id desc;

答案 1 :(得分:1)

我可能会这样写:

SELECT ts.id, t.id, t.name
       FROM table1 ts
            INNER JOIN tabble2 t 
                   ON ts.ta = t.ta
                    AND ts.id = :var1
                    AND (:var1 = 0 OR ts.em = :var2)
                     ORDER BY ts.id desc;