2011-03-20 79 views
0

我想插入一些數據到數據庫中。在插入過程中,我想首先做出一個判斷:如果title1不存在於table1和table2中,則插入。如何寫這個雙重句子?這是正確的嗎?或...謝謝。php從哪裏選擇多對偶

mysql_query(" 
INSERT INTO table1 title 
SELECT '".$title."' 
FROM dual 
WHERE not exists (
    SELECT title 
    FROM table1 
    WHERE table1.title = '".$title."' 
) AND (
    SELECT title 
    FROM table2 
    WHERE table2.title = '".$title."' 
) "); 
+0

子查詢的WHERE子句可以提高查詢的執行時間,如果你得到了在「雙反」表中的許多行。 – 2011-03-20 11:31:04

+0

@Piotr Salaciak,那麼如何以正確的方式書寫? – 2011-03-20 11:41:53

回答

3

首先,MySQL不使用dual表。只需直接選擇值。通常情況下,以插入一個表格,您只需要爲使用

INSERT INTO table1(title) SELECT 'something'; # or 
INSERT INTO table1(title) VALUES ('something'); 

但是,下面的使用由表(化名TT),以便能夠使用留在其加入到其它表。

mysql_query(" 
    INSERT INTO table1(title) 
    SELECT theTitle 
    FROM (SELECT '".$title."' theTitle) TT 
    LEFT JOIN table1 ON table1.title = TT.theTitle 
    LEFT JOIN table2 ON table2.title = TT.theTitle 
    WHERE table1.title is null and table2.title is null 
"); 

你也可以完成您的NOT EXISTS子句

mysql_query(" 
    INSERT INTO table1(title) 
    SELECT '".$title."' 
    WHERE NOT EXISTS (SELECT * FROM table1 WHERE title = '".$title."') 
     AND NOT EXISTS (SELECT * FROM table2 WHERE title = '".$title."') 
"); 

但我更喜歡前者,因爲這需要你使用$冠軍3次。

1
mysql_query("INSERT INTO table1 title 
       SELECT '".$title."' FROM dual 
       WHERE not exists (SELECT title FROM table1 WHERE table1.title = '".$title."') AND 
        not exists (SELECT title FROM table2 WHERE table2.title = '".$title."') "); 

失蹤查詢第二not exists

0

聯盟任何人嗎?

mysql_query(" 
INSERT INTO table1 title 
SELECT '".addSlashes($title)."' 
FROM dual 
WHERE not exists (
    SELECT title 
    FROM table1 
    WHERE title = '".addSlashes($title)."' 
    UNION 
    SELECT title 
    FROM table2 
    WHERE title = '".addSlashes($title)."' 
) ");