MySQL插入不带条件语句的地方

时间:2012-03-31 23:01:12

标签: mysql mysql5 mysql-5.0

目标:

  • 仅使用MySQL,当sku& amp;时,插入sku,tablename,slugs表。表名尚未设置。我有多个表可以有相同的sku,但它们不一样。所以它需要匹配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.

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;

破解MySQL代码

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

2 个答案:

答案 0 :(得分:0)

很遗憾,您无法插入表格并从子查询中的同一个表格中进行选择,但如果您对skutablename列有唯一约束,则可以使用INSERT IGNORE INTO ...得到同样的效果。

答案 1 :(得分:0)

我能够使用以下内容实现此功能。感谢jRC中的j_wright

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'
);

---或者这些工作-------

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