0

Basically trying to fill a table with product codes from another table. The codes can be repeated in the Products table, as it has data about product sizes, however this value needs to be unique in ProductDescriptions.

I need there to be a new entry into the ProductDescriptions table every time there is a new DISTINCT product code in the Products table.

I've tried all sorts of things with no success, doesn't seem to that complex however its baffled me.

I have tried this:

INSERT INTO ProductDescriptionsbackup(ProductID) SELECT DISTINCT `PRODUCT CODE` FROM Products

However it doesn't run as it can't just take the DISTINCT values, and in the long run it doesn't update automatically, however that would be a secondary issue.

The main issue is getting the DISTINCT values into the ProductDescriptions table.

I've had a look around for answers but theres been nothing that stood out and made sense to me. Thanks in advance for any help received.

4

2 回答 2

1

If you are only trying to insert new values, this should work. You could make a left join to the target table and only include records that don't exist (WHERE pbu.ProductID IS NULL).

INSERT INTO ProductDescriptionsbackup(ProductID) 
SELECT DISTINCT p.`PRODUCT CODE` 
FROM   Products as p
       LEFT JOIN ProductDescriptionsbackup as pbu
       ON p.`PRODUCT CODE` = pbu.ProductID
WHERE  pbu.ProductID IS NULL;
于 2013-06-27T16:25:30.020 回答
1

Lets break your question is two parts. First is to garanteee that ProductDescriptions is always updated when you insert a new row in the products, the second is how to insert the new values.

For the first part there are two option, you're responsible in the code to explicit insert the productdescription every time and everywhere you do a insert into the product table or you can create a trigger after insert to do that

create trigger ai_eav
after insert on eav
for each row
(...)

I recommend this second option so you won't forget to insert, but there are some folks that don't like triggers since they can become "invisible" to the programmer as they are usually forgotten.

For the second part, you can do a insert if not exists, which could be achieved by doing a insert with a left join

insert into ProductDescriptions(ProductID)
select distinct p.`PRODUCT CODE` 
from Products 
left join join ProductDescriptions on `PRODUCT CODE` = ProductID
where ProductID is null

if you opt for the trigger you can even take advantage of the pseudo row new and make the insert even faster since you'll be working with a single row, instead of working with the whole products table.

于 2013-06-27T16:32:54.577 回答