我正在试图弄清楚如何在where子句中使用case语句(使用!=),这里是我想要做的事情的想法:
SELECT *
FROM Table1 JOIN Table2 JOIN Table3
WHERE
CASE @fruit
WHEN 'Apples' THEN (What would go here to return only data related to apples in Table1?)
WHEN 'Citrus' THEN (What would go here to return data related to either oranges or lemons in Table2?)
WHEN 'Other' THEN (return all data not related to apples, oranges, or lemons from all 3 tables) (!=)
END
我在where子句中看到了一些case语句的例子,但没有一个带有!= condition的例子。有什么想法吗?
答案 0 :(得分:2)
一个简单的AND
/ OR
组合可以:
SELECT *
FROM Table
WHERE
(@fruit != 'Other' AND Fruit = @fruit) OR
(@fruit = 'Other' AND Fruit NOT IN('Apples', 'Oranges')
答案 1 :(得分:1)
如果我理解你的问题,你想要评估除了相等之外的其他布尔表达式。 mongo ds151461.mlab.com:51461/simplelogin -u myuser -p mypassword
语句有两种形式,一种是你正在尝试的(总是寻找相等)和另一种形式:
CASE
答案 2 :(得分:0)
只需将ELSE用于其他一切
SELECT *
FROM Table
WHERE
CASE @fruit
WHEN 'Apples' THEN (What would go here to return only data related to apples?)
WHEN 'Oranges' THEN (What would go here to return only data related to oranges?)
ELSE (return all data not related to apples or oranges) (!=)
END
或者您可以使用案例中的参数,例如
SELECT *
FROM Table
WHERE
CASE
WHEN @fruit = 'Apples' THEN (What would go here to return only data related to apples?)
WHEN @fruit = 'Oranges' THEN (What would go here to return only data related to oranges?)
WHEN @fruit <> 'Apples' AND @fruit <> 'Oranges' THEN (return all data not related to apples or oranges) (!=)
END