【问题标题】:Insert only unique records in SQL在 SQL 中只插入唯一记录
【发布时间】:2021-01-15 16:41:10
【问题描述】:

我在 SQL 中运行以下查询以插入记录(这只是一个 sn-p)

insert into list_member (list_id, list_int_value , list_float_value , list_decimal_value , list_varchar_value, list_datetime_value, modified_by, asof_time, do_not_audit)
select 42, null, null, security_id, null, null, 10, null, null
from security
 where not exists(select user_id_4 from list_member.user_id_4 where list_member.user_id_4  = security.user_id_4)
 and deleted = 0 and user_id_4 in
(
'ES0125220311',
'ES0132105018',
'ES0167050915'
)

现在我要插入另一个列表,但只想插入新记录。

我不确定在哪里插入额外的“where”子句,以免插入重复项。我想出了下面的(理论上应该只添加最终记录),但是粗体的附加 where 子句可能是错误的......

insert into list_member (list_id, list_int_value , list_float_value , list_decimal_value , list_varchar_value, list_datetime_value, modified_by, asof_time, do_not_audit)
select 42, null, null, security_id, null, null, 10, null, null
from security
 **where not exists(select user_id_4 from list_member.user_id_4 where list_member.user_id_4  = security.user_id_4)**
 and deleted = 0 and user_id_4 in
(
'ES0125220311',
'ES0132105018',
'ES0167050915',
'ES0123456789'
)

有人可以帮忙吗?

【问题讨论】:

  • 用您正在使用的数据库标记您的问题。
  • “加粗的 where 子句可能是错误的”。你为什么这么说?当你尝试它时发生了什么?
  • 我遇到了语法错误,但我已经对其进行了更改以使其现在可以正常工作。

标签: sql sql-server-2016


【解决方案1】:

我改成这个了

left join list_member 
   on list_member.list_id = 42 and list_member.list_decimal_value  = security.security_id

抱歉给您添麻烦了。

【讨论】:

    【解决方案2】:

    您可以按如下方式使用相关查询:

    insert into list_member (list_id, list_int_value , list_float_value , list_decimal_value , list_varchar_value, list_datetime_value, modified_by, asof_time, do_not_audit)
    select 42, null, null, security_id, null, null, 10, null, null
    from security s
    where not exists
      (select 1 from list_member l where l.user_id_4  = s.user_id_4)
     and deleted = 0 and user_id_4 in
    (
    'ES0125220311',
    'ES0132105018',
    'ES0167050915',
    'ES0123456789'
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-02
      • 2011-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-18
      • 1970-01-01
      相关资源
      最近更新 更多