如果条件,在mysql中执行语句

时间:2017-08-11 06:40:07

标签: mysql

我在以下查询中遇到问题。 Eveytime查询运行成功条件,它直接打印语句而不是执行。我很震惊,我不知道如何解决它。任何人都可以指导我如何修复以下查询

SELECT IF(
        (SELECT COUNT(*)
                FROM INFORMATION_SCHEMA.VIEWS
                WHERE table_name = 'user_details'
                AND table_schema = 'user_details'
        ) = 0 AND
        (SELECT COUNT(*)
                FROM INFORMATION_SCHEMA.COLUMNS
                WHERE table_name = 'mobile_consumer'
                AND table_schema = DATABASE()
                AND column_name IN ('payment_ref', 'pp', 'tt')
        ) = 3,
        "Select * from users_details",
        "Select 0"
)

上面查询的Sql输出显示为“select * from users_details”,但我想要的是该语句应该执行并显示表的行。任何建议??

1 个答案:

答案 0 :(得分:2)

我猜您忘记在代码中使用THEN子句。此外,您已编写了要在IF块中执行的语句,其中应在THEN块中写入。 另一件事是你用“”编写了你的​​查询,这使得它们是一个简单的字符串,将按原样打印,而不是在没有引号的情况下编写它们,如果你需要将它们与代码的其余部分隔离,请使用括号。您的更新代码如下所示。

IF
   (SELECT COUNT(*)
           FROM INFORMATION_SCHEMA.VIEWS
           WHERE table_name = 'user_details'
           AND table_schema = 'user_details'
   ) = 0
   AND
   (SELECT COUNT(*)
           FROM INFORMATION_SCHEMA.COLUMNS
           WHERE table_name = 'mobile_consumer'
           AND table_schema = DATABASE()
           AND column_name IN ('payment_ref', 'pp', 'tt')
   ) = 3

Then
    (Select * from users_details)
ELSE
    (Select 0)
END IF

或者,如果您有多个语句要针对多个条件执行,您可以尝试使用case语句来评估您的条件。

SELECT
    CASE WHEN 
        count1 = 0 AND count2 = 3 
    THEN 
        (Select * from users_details)
    ELSE
        (Select 0)
    END

FROM
(
    SELECT
        (SELECT COUNT(*) FROM INFORMATION_SCHEMA.VIEWS WHERE table_name = 'user_details' AND table_schema = 'user_details') AS count1,
        (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = 'mobile_consumer' AND table_schema = DATABASE() AND column_name IN ('payment_ref', 'pp', 'tt')) AS count2
) 
    AS counts

如果它解决了您的问题,请标记为已接受。