MySQL 过程仅在不存在时插入

标签 mysql stored-procedures

我正在使用 MySQL 存储过程,我想通过存储过程将一些行从表的数据库插入到另一个表的数据库。更具体地说,从数据库“new_schema”、表“Routers”和字段“mac_address”到数据库“data_warehouse2”、表“dim_cpe”和字段“mac_address”。

这是我在第一次插入时使用的代码,效果很好。

insert into data_warehouse2.dim_cpe (data_warehouse2.dim_cpe.mac_address, data_warehouse2.dim_cpe.ssid)
(select new_schema.Routers.mac_address, new_schema.Routers.ssid from new_schema.Routers, data_warehouse2.dim_cpe);

现在我在表“Routers”中有更多行要插入到“dim_cpe”中,但是由于那里已经有行,我只想插入新行。

正如在其他帖子中看到的,我尝试了一个 where 子句:

where new_schema.device_info.mac_address != data_warehouse2.dim_cpe.mac_address

和一个:

on duplicate key update new_schema.Routers.mac_address = data_warehouse2.dim_cpe.mac_address"

两者都不起作用。最好的方法是什么?

提前致谢。

最佳答案

您可以将源表保留在 from 子句之外,并使用 not contains 子句来代替:

where not exists
(select mac_address from dim_cpe mac_address = new_schema.Routers.mac_address
and ssid = new_schema.Routers.ssid)

或者您可以离开 join 并检查 dim_cpe 中的字段是否为空:

insert into data_warehouse2.dim_cpe
(data_warehouse2.dim_cpe.mac_address, data_warehouse2.dim_cpe.ssid)
(select new_schema.Routers.mac_address, new_schema.Routers.ssid
from new_schema.Routers
  left join data_warehouse2.dim_cpe on
    new_schema.Routers.mac_address = data_warehouse2.dim_cpe.mac_address
    and new_schema.Routers.ssid = data_warehouse2.dim_cpe.ssid
where dim_cpe.mac_address is null and dim_cpe.ssid is null);

编辑说这是一个通用的 SQL 解决方案。我不确定是否有更好的特定于 MySql 的方法。

编辑以显示您的查询:

insert into data_warehouse2.dim_cpe (mac_address, ssid)
select new_schema.Routers.mac_address, new_schema.Routers.ssid
from new_schema.Routers where not exists
    (select data_warehouse2.dim_cpe.mac_address from data_warehouse2.dim_cpe
    where data_warehouse2.dim_cpe.mac_address = new_schema.Routers.mac_address
       and data_warehouse2.dim_cpe.ssid = new_schema.Routers.ssid);

关于MySQL 过程仅在不存在时插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33804789/

相关文章:

c++ - 如何用C++(Linux下)连接MYSQL数据库(WINDOWS下)

java - 使用 jdbc 从 mssql 存储过程获取结果

tsql - 如何动态停止/触发存储过程中的触发器?

mysql - 来自已知点查询的 SQL 位置

mysql - 使用 mysql 检索地址的最佳方法

mysql - 设计 MySQL 数据库的技巧

php - 将挂单分成两组

database - Google Cloud Spanner 是否支持存储过程?

mysql - 哪些已经存在的drop程序?

sql - 使用输入参数为存储过程创建 SQL Server 代理作业