0

I am using MySQL. I want to insert some records in a table provided that they do not exist in another table. So I want to perform something like this:

INSERT INTO sales (name, id)
SELECT name, id FROM sales_h 
WHERE name AND id NOT IN (SELECT name, id FROM T_sales);

The problem is that MySQL does not allow this kind of syntax (something to do with the where clause...) I tried using CONCAT but with no result.

Any clue??

4

7 回答 7

1
INSERT
INTO    sales (name, id)
SELECT  name, id
FROM    sales_h
WHERE  (name, id) NOT IN
       (
       SELECT name, id
       FROM t_sales
       )
于 2009-04-06T13:31:19.413 回答
1

您是否尝试过EXISTS 语法

INSERT INTO sales (name, id) 
SELECT name, id 
FROM sales_h 
WHERE NOT EXISTS (SELECT * FROM T_sales WHERE T_sales.name = sales_h.name AND T_sales.id = sales_h.id);
于 2009-04-06T13:33:14.260 回答
1

MySQL 允许您像变量一样使用元组:

这是你的声明:

INSERT INTO sales (name, id)
SELECT name, id FROM sales_h 
WHERE name AND id NOT IN (SELECT name, id FROM T_sales);

问题是“姓名和身份证”。把它变成一个元组:

INSERT INTO sales (name, id)
SELECT name, id FROM sales_h 
WHERE (name, id) NOT IN (SELECT name, id FROM T_sales);

就个人而言,我不太喜欢这个有两个原因:元组作为变量在其他 RDBMS 上不起作用(或工作方式不同),并且 IN 在许多情况下往往表现不佳,所以我喜欢养成不做的习惯用于。

正如 jhonny-d-cano-leftware 所说(我已经升级了他),我会使用 where not exists :

INSERT INTO sales (name, id)
SELECT name, id FROM sales_h a
WHERE not exists (
 SELECT * 
 FROM T_sales b 
 where b.id = a.id and b.name = a.name);
于 2009-04-06T13:51:47.167 回答
0

您可能会查看ON DUPLICATEMySql 的子句

http://dev.mysql.com/doc/refman/5.1/en/insert-select.html

于 2009-04-06T13:30:41.070 回答
0

你不能说 WHERE name AND id NOT IN... 你需要为每个单独的子句。但是你有 id 作为表 T_sales 中的主键吗?如果是这样,那么这就是您需要检查的所有内容,例如:

INSERT INTO sales (name, id) 
(SELECT name, id FROM sales_h WHERE id NOT IN (SELECT id FROM T_sales));

编辑

嗯,从其他人的回答来看,最好忽略我,因为他们似乎知道更多:-)

于 2009-04-06T13:30:54.157 回答
0

问题是你的 WHERE。

它不像你那样阅读。您将其读作“WHERE (name and id) NOT IN (...)”,而将其读作“WHERE name (isn't null) AND (id NOT IN (...))”.. . 如果你明白我的意思。

改成这样:ROW(name, id) NOT IN (SELECT name, id FROM T_sales);

于 2009-04-06T13:31:30.413 回答
0
INSERT INTO table_name(column1, column2) SELECT "value one", "value two" FROM DUAL
WHERE NOT EXISTS(
    SELECT column1 FROM table_name
    WHERE column1 = "value one"
    AND column2 = "value two" LIMIT 1
)
于 2009-08-03T08:55:00.020 回答