简体   繁体   中英

mysql insert into not work

I want insert 4 datas into 4 fields and checked if 2 of them have not exists. (the data match `pid = '1' and sid '123')

Here is my code, I checked several times, my mysql connect is well, my database is right, these four fields in my table . but I just can not insert. there has no warning return page.

require ("connect.php");// this one I always test on my localhost, no proble, even require on other page, all works well
mysql_select_db("test",$database_link);
mysql_query("SET NAMES utf8");
mysql_query("INSERT INTO user_data (uid, pid, sid, wid)  SELECT  '123456', '1', '123', '2' FROM dual WHERE not exists (SELECT pid,sid FROM user_data WHERE user_data.pid = '1' AND  user_data.sid = '123')");

for see clearlly:

INSERT INTO user_data (uid, pid, sid, wid) 
SELECT '123456', '1', '123', '2' 
FROM dual 
WHERE NOT EXISTS
(
    SELECT pid, sid 
    FROM user_data 
    WHERE user_data.pid = '1' 
    AND user_data.sid = '123'
)

Error message:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'pid, sid, wid) SELECT '123456', '1', '123', '2' FROM dual WHERE not exists (SE' at line 1

Query works fine on MySQL 5.1.54.

From docs :

The target table of the INSERT statement may appear in the FROM clause of the SELECT part of the query. (This was not possible in some older versions of MySQL.) However, you cannot insert into a table and select from the same table in a subquery.

When selecting from and inserting into a table at the same time, MySQL creates a temporary table to hold the rows from the SELECT and then inserts those rows into the target table. However, it remains true that you cannot use INSERT INTO t ... SELECT ... FROM t when t is a TEMPORARY table, because TEMPORARY tables cannot be referred to twice in the same statement (see Section C.5.7.2, “TEMPORARY Table Problems”).

Could this be the reason?

It could be a duplicate name problem on the tables, try to use alias :

INSERT INTO user_data (uid, pid, sid, wid) 
SELECT '123456', '1', '123', '2' 
FROM dual 
WHERE NOT EXISTS 
(
    SELECT NULL -- don't need to select fields in a NOT EXISTS clause
    FROM user_data u2
    WHERE u2.pid = '1' 
    AND u2.sid = '123'
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM