MySQL insert where not with conditional statement

153 Views Asked by At

Objective:

  • Using only MySQL, insert sku, tablename, slugs table when a sku & table name are not not already set. I've got multiple tables that can have the same sku, but they are not the same. So it needs to match on sku + tablename.
 table1
      SKU = 123
      SKU = 234
table2
  SKU = 1234
  SKU = 123
  SKU = 45234

slugs final result should be like

slugs
  sku = 123 , table = table1
  sku = 234 , table = table1
  sku = 1234, table = table2
  sku = 123, table = table2
  sku = 45334, table = table2

I need to be able to look up sku's based off of the table name.

tables

CREATE TABLE `slugs` (
  `id` bigint(20) NOT NULL,
  `slug` varchar(500) default NULL,
  `tablename` varchar(129) default NULL,
  `sku` varchar(100) default NULL,
  `deleteme` tinyint(4) NOT NULL default '0',
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

CREATE TABLE `tableA` (
  `NAME` varchar(160) default NULL COMMENT 'The products name.',
  `SKU` varchar(100) NOT NULL default '' COMMENT 'Advertisers unique identifier for the product.',
  PRIMARY KEY  (`SKU`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

Broken MySQL code

INSERT INTO `slugs` (`sku`, `tablename`)
Select `SKU`, 'tableA'
from `tableA`
where not exists
(SELECT `slugs`.`sku` !=  `tableA`.`SKU` AND `slugs`.`tablename` !=  'tableA'); 
2

There are 2 best solutions below

5
On

Unfortunately you cannot insert into a table and select from the same table in a subquery, but if you have a unique constraint on the sku and tablename columns then you can use INSERT IGNORE INTO ... to get the same effect.

0
On

I was able to get this to work using the following. Thanks to j_wright in an iRC

INSERT INTO `slugs` (`sku`, `tablename`)
SELECT `SKU`, 'tableA', `NAME` FROM `tableA`
WHERE NOT EXISTS (
     SELECT `sku`, `tablename` FROM `slugs`
     WHERE `sku` = `tableA`.`SKU` and `tablename` = 'tableA'
);

---OR THIS SEEMS TO WORK-------

INSERT INTO `slugs` (`sku`, `tablename`)
select `SKU`, 'tableA'
from `tableA`
WHERE `SKU` NOT IN
(select `sku` from `slugs` where `tablename` = 'tableA');