简体   繁体   中英

MySQL Insert Query with Foreign Key

I want to insert a value in table glmast in the field called acname.

The conditions I am using is as follows

g.gl_id = p.gl_id AND p.pl_id='$pdidedit' with g as glmast and p as packlist

I tried joins, and try the below code..

INSERT INTO glmast (acname)
VALUES
('$glidnew') SELECT glmast.acname WHERE glmast.gl_id = packlist.gl_id AND packlist='$pdidedit'";

Any help highly appreciated..Thanks everyone..

You can write insert like

INSERT INTO glmast (acname) VALUES ('$glidnew');

or

INSERT INTO glmast (acname)
SELECT glmast.acname from glmast,packlist 
  WHERE glmast.gl_id = packlist.gl_id
    AND packlist.gl_id = '$pdidedit'";

Have in mind that in second example there could be multiple inserts in cases when select returns multiple rows.

I think this may be what you're trying to do:

INSERT INTO glmast(gl_id, acname)
SELECT '$glidnew', glmast.acname
FROM glmast JOIN packlist ON glmast.gl_id = packlist.gl_id
WHERE packlist.pl_id='$pdidedit'

You keep saying INSERT, but I'm pretty sure you mean UPDATE:

UPDATE glmast g
JOIN packlist p ON g.gl_id = p.gl_id
SET g.acname = '$glidnew'
WHERE p.pl_id = '$pdidedit'

Or maybe this is it:

INSERT INTO glmast (acname, col1, col2, col3, ...)
SELECT '$glidnew', g.col1, g.col2, g.col3, ...
FROM glmast g
JOIN packlist p ON g.gl_id = p.gl_id
WHERE p.pl_id = '$pdidedit'

I belive it's something like this you're trying to achieve :

INSERT INTO glmast (acname) VALUES('$glidnew')
WHERE (
    SELECT glmast.acname FROM glmast GM
    JOIN packlist PL ON (PL.gl_id = GM.gl_id)
    WHERE PL.pl_id='$pdidedit'
)

But that syntax is not valid in MySQL. You will have to run the SELECT-statement first, and then INSERT into the glmast table based on resultset given from SELECT-query:

Step 1:

SELECT glmast.acname FROM glmast GM
JOIN packlist PL ON (PL.gl_id = GM.gl_id)
WHERE PL.pl_id='$pdidedit'

Step 2:

INSERT INTO glmast (acname) VALUES({values from Step1})

In a way, you can say that $glidnew represents the values from Step1.

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