MySQL检查表存在IF函数

时间:2016-05-20 14:23:37

标签: mysql

SELECT IF((
    SELECT COUNT(TABLE_NAME)
    FROM information_schema.tables 
    WHERE TABLE_SCHEMA='database0' AND TABLE_NAME='table'
) >0 , (
    SELECT id 
    FROM database1.table 
    WHERE id NOT IN (SELECT id FROM database0.table)
), NULL) AS pk_value;

database0.table可能不存在;如果该表不存在,我想跳过true语句的IF子句。即使IF语句应该返回NULL,我也会收到database0.table不存在的错误。如果表不存在,我该怎么做才能使查询返回NULL而不是抛出错误?

1 个答案:

答案 0 :(得分:0)

如评论中所述,查询在运行之前会进行错误检查,因此引用不存在的表将不起作用。您可以将其存储为一个函数,该函数仅在运行时进行评估:

DROP FUNCTION IF EXISTS get_pk;
DELIMITER //

CREATE FUNCTION get_pk()
RETURNS INT

BEGIN
    DECLARE counter INT;
    DECLARE pk_value INT;

    SELECT COUNT(table_name) INTO counter
    FROM information_schema.tables
    WHERE table_schema = 'database0' AND table_name = 'table';

    IF counter = 1 THEN
        SELECT id INTO pk_value
        FROM database1.table 
        WHERE id NOT IN (SELECT id FROM database0.table);
    ELSE
        SELECT NULL INTO pk_value;
    END IF;

    RETURN pk_value;
END//

DELIMITER ;

然后访问这样的值:

SELECT get_pk();