在SQL中返回1或0,具体取决于多个语句

时间:2018-03-14 14:32:20

标签: mysql sql

如果我发现某些用户存在这样的参数,我希望得到1否则为0.将来我将不得不添加更多的块。但它现在似乎不起作用。我做错了什么?

 SELECT CAST(CASE WHEN EXISTS(SELECT 1
                              FROM Customers
                              WHERE Country = 'France' AND PostalCode%2 = 0)
                              OR (WHERE Country = 'Germany' AND PostalCode%2 = 0))
                              ) 
                  THEN 1 
                  ELSE 0 
              END AS BIT)

2 个答案:

答案 0 :(得分:2)

您需要两个单独的exists

SELECT CAST(CASE WHEN EXISTS (SELECT 1
                              FROM Customers
                              WHERE Country = 'France' AND PostalCode%2 = 0
                             )
                 THEN 1
                 WHEN EXISTS (SELECT 1
                              FROM Customers
                              WHERE Country = 'Germany' AND PostalCode%2 = 0
                             )
                 THEN 1
                 ELSE 0
            END AS BIT)

实际上,我把它分成两个单独的THEN条款。这几乎等同于使用OR,但由于逻辑位于CASE内,THEN似乎更自然。 (不同之处在于优化器可以选择重新排列OR条件,但THEN条件以词法顺序执行。)

如果您的陈述实际上很简单,您可以将它们组合为:

SELECT CAST(CASE WHEN EXISTS (SELECT 1
                              FROM Customers
                              WHERE Country IN ('France', 'Germany') AND PostalCode%2 = 0
                             )
                 THEN 1
                 ELSE 0
            END AS BIT)

答案 1 :(得分:0)

在我看来,您只是遇到了包围问题:

This is a 
very long 
sentence t
hat needs 
to be chun
ked up

根据戈登的假设,SELECT CAST( CASE WHEN EXISTS( SELECT 1 FROM Customers WHERE (Country = 'France' AND PostalCode%2 = 0) OR (Country = 'Germany' AND PostalCode%2 = 0) ) THEN 1 ELSE 0 END AS BIT) 对于所有经过测试的“条件”(你还没有说过),你也可以将其缩短为:

PostalCode%2 = 0