Question

I'm having a problem trying to insert some values into a table. I made an empty table with the fields

id(primary key) 
association_id 
resource_id

I have another table with

resource_id
association_id

and another one with

id(coresponding to the association_id in the former one)
image

I want to insert the resource_id and association_id from the first populated table, where the image field of the coresponding id from the last table is not empty.

I tried this:

INSERT IGNORE INTO `logo_associations` (``,`association_id`,`resource_id`)
SELECT 
        ``,
        `a`.`association_id`,
        `a`.`resource_id`
FROM doc24_associations_have_resources a
Join doc24_associations    An on a.association_id = An.id 
WHERE An.image<>''

but it does not work

Was it helpful?

Solution 2

My experience is based on SQL Server but the SQL may be very similar

 INSERT INTO DestinationTable
        (association_id, resource_id)
 SELECT LNK.assocication_id,
        LNK.resource_id
   FROM LinkTable AS LNK
        INNER JOIN ImageTable AS IMG ON IMG.id = LNK.association_id
                   AND IMG.image IS NOT NULL

Above I assume the following:

  1. Tables are named DestinationTable, LinkTable, and ImageTable respectively
  2. In DestinationTable the primary key (id) is auto generated

OTHER TIPS

Try this:

INSERT INTO logo_associations (association_id, resource_id)
SELECT a.association_id
      ,a.resource_id
FROM doc24_associations_have_resources a
LEFT JOIN doc24_associations an ON a.association_id = an.id 
WHERE an.image IS NULL -- check for null with left join

This is valid for SQL Server. You do not need to select and insert the first column as it is an identity as you mention.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top