使用select语句插入

时间:2014-03-04 08:00:17

标签: mysql sql-server-2008

我有一个我无法完全理解的查询。我用mysql v.5.5测试它并且什么也没得到。 这是片段:

INSERT INTO
            logs (
                f1,
                f2,
                f3,
                f4,
                f5,
                f6
            )
        SELECT
                'test',
                'done',
                'test',
                'test',
                'test',
                'test'
        FROM
            logs
        WHERE
            NOT EXISTS (
                SELECT * FROM
                        logs
            WHERE
                f1 = 'test' and
                f2 = 'done' and
                f3 = 'test' and
                f4 = 'test' and
                f5 = 'test' and
                f6 = 'test'
            )
        LIMIT 1

我所理解的是,其他表中的字段可以被选中和默认,但我不明白的是为什么不是字段,而是选择字段值。这是在以前版本的MySQL中可用吗?另外..我需要在SQL Server 2008中运行适当的查询。任何解释?感谢。

1 个答案:

答案 0 :(得分:1)

此SQL在表logs中插入一行,其值为

 f1 = 'test' and
 f2 = 'done' and
 f3 = 'test' and
 f4 = 'test' and
 f5 = 'test' and
 f6 = 'test'

如果表中不存在具有该值的行。

INSERT INTO
        logs (
            f1,
            f2,
            f3,
            f4,
            f5,
            f6
        )
        -- Here we're specifying which value will have every field
    SELECT
            'test',
            'done',
            'test',
            'test',
            'test',
            'test'
    FROM
        logs
    WHERE
        -- Here we're looking into the table 'logs' for the row with that values.
        -- If we match the condition we'll insert into the table
        NOT EXISTS (
            SELECT * FROM
                    logs
        WHERE
            f1 = 'test' and
            f2 = 'done' and
            f3 = 'test' and
            f4 = 'test' and
            f5 = 'test' and
            f6 = 'test'
        )
    LIMIT 1

关于版本,从MySQL 5.0开始提供:https://dev.mysql.com/doc/refman/5.0/en/insert-select.html,甚至MySQL 4.1:http://dev.mysql.com/doc/refman/4.1/en/insert-select.html

关于SQL,我很抱歉,从来没有使用它,但肯定会有类似的句子,你可以查看这个问题:Insert into ... values ( SELECT ... FROM ... )

相关问题