开发者

php select from where multi dual

I want to insert some data into database. During the insert, I want to make a judge first: if title not exist in table1 and table2, then insert. how to write this dual sentence? Is this right? OR..开发者_JAVA百科. Thanks.

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."'
) ");


First of all, MySQL does not use the dual table. Just select the value directly. Normally to insert into a table, you only need to use either

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

However, the below uses a made up table (aliased TT) to be able to use a LEFT JOIN on it to other tables.

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
");

You can also just complete your NOT EXISTS clauses

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."')
");

But I prefer the former, because this requires you to use $title 3 times.


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."') ");

missing second not exists in query.


Union anyone?

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)."'
) ");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜