2014-03-04 137 views
0

我有一个查询,我不能完全理解。我用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 

我明白了什么是从其他表中的字段可以选择和iserted,但我不明白的是为什么没有选择的字段,但是字段值。这在以前版本的MySQL中可用吗?另外..我需要一个适当的查询在SQL Server 2008中运行。任何解释?谢谢。

回答

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,对不起,从来没有与它的工作,但肯定会有一个类似的句子,你可以看看这个SO问题:Insert into ... values (SELECT ... FROM ...)

+0

很酷的解释。顺便说一句,我试图从中提取select(from where)部分,结果是select语句中的值被视为列名。这是好吗? –

+0

如果你只提取select,你什么也没做。选择一个字符串就是字符串。如果你想将值赋值为一个字段,你可以'SELECT'字符串'AS f1',这会给你一个'string'作为值的f1字段 – Chococroc

+0

我试过这样做,看看http:// screencloud .net/v/4DnE –