简体   繁体   中英

SELECT FROM one table and INSERT INTO another; using WHERE & AND

INSERT INTO tblPubInfo i (img_name)
SELECT f.img_name
FROM tblPubFiles f 
WHERE f.img_name<>''
AND f.pub_uid = i.uid

this is what I am trying to do but it is giving me a error. What is wrong with it and how to fix it?

Your are referencing the target table in Your condition (i.uid). This is not allowed, because it does not appear in the tables (from clause).

It's a bit hard to help you without supplying the error.

However, if your database is MySQL,

MySQL doesn't support ALIAS on INSERTS

INSERT INTO tblPubInfo i (img_name)

should be:

INSERT INTO tblPubInfo (img_name)

see here:

http://dev.mysql.com/doc/refman/5.1/en/insert.html

Shouldn't that be:

INSERT INTO tblPubInfo (img_name)
SELECT f.img_name
FROM tblPubFiles f, tblPubInfo i
WHERE f.img_name<>''
AND f.pub_uid = i.uid

Seems like you are trying to update a recored with an insert into statement. That doesn't work. Use the following:

UPDATE tblPubInfo i
SET i.img_name = ( SELECT f.img_name 
                   FROM   tblPubFiles f 
                   WHERE  f.img_name is not null 
                   AND    f.pub_uid = i.uid
                 )

You need to join the two tables in the Select clause, in order to use the alias i for the table tblPubInfo like:

INSERT INTO tblPubInfo (img_name) 
SELECT f.img_name
FROM tblPubFiles f 
inner join tblPubInfo i on f.pub_uid = i.uid
WHERE f.img_name <> ''

try this:

INSERT INTO tblPubInfo (img_name) 
SELECT a.img_name
FROM   tblPubFiles a INNER JOIN tblPubInfo b ON a.pub_uid = b.uid
WHERE  CHAR_LENGTH(TRIM(a.img_name)) > 0

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