Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Where Not Exists not working

Tags:

sql

mysql

I have two tables called TEMPDATA and Product. I am dumping all my data from a csv feed into TEMPDATA and then organising it into the respective tables, Product being one of them.

I am trying to insert all the contents of TEMPDATA that does not have a duplicate 'ean' number into Product, providing it doesn't already exist in Product.

The query I am trying to use is below...

INSERT IGNORE INTO `Product` (`product_ean`, `product_name`, `product_description`, `product_image`, `product_thumbnail`, `product_category`) 
SELECT `ean`, `product_name`, `description`, `merchant_image_url`, `aw_thumb_url`, `merchant_category` 
FROM (
    SELECT `ean`, `product_name`, `description`, `merchant_image_url`, `aw_thumb_url`, `merchant_category`, count( * ) 
    FROM TEMPDATA
    GROUP BY `ean`
    HAVING count( * ) = 1
) AS t
WHERE NOT EXISTS (
    SELECT `product_ean` FROM Product
)

All the individual sections seem to be working, except from when I include the 'WHERE NOT EXISTS' clause, could someone please help me out?

like image 994
Phil Avatar asked Dec 01 '25 20:12

Phil


2 Answers

try this:

    INSERT IGNORE INTO Product (product_ean, product_name, product_description, product_image, product_thumbnail, product_category) 
SELECT ean, product_name, description, merchant_image_url, aw_thumb_url, merchant_category 
FROM (
    SELECT ean, product_name, description, merchant_image_url, aw_thumb_url, merchant_category, count( * ) 
    FROM TEMPDATA
    GROUP BY ean
    HAVING count( * ) = 1
) AS t
WHERE NOT EXISTS (
    SELECT product_ean FROM Product AS A WHERE A.product_ean = t.product_name
)

you were missing this:

WHERE A.product_ean = t.product_name

in the NOT EXIST statement

like image 178
Fuzzy Avatar answered Dec 04 '25 15:12

Fuzzy


you need to make you include the the where clause to search, see below

    INSERT IGNORE INTO `Product` (`product_ean`, `product_name`, `product_description`, `product_image`, `product_thumbnail`, `product_category`) 
SELECT `ean`, `product_name`, `description`, `merchant_image_url`, `aw_thumb_url`, `merchant_category` 
FROM (
    SELECT `ean`, `product_name`, `description`, `merchant_image_url`, `aw_thumb_url`, `merchant_category`, count( * ) 
    FROM TEMPDATA
    GROUP BY `ean`
    HAVING count( * ) = 1
) AS t
WHERE NOT EXISTS (
    SELECT `product_ean` FROM Product P where t.ean = p.`product_ean`
)
like image 40
akhil vangala Avatar answered Dec 04 '25 16:12

akhil vangala



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!