如果某个名称不在列中则 SQL 插入

发布于 2025-01-13 03:22:55 字数 466 浏览 2 评论 0原文

我想在表中插入记录:

UserTypeUserNameValid
Type1Name1True

目前我使用的是以下sql代码:

insert into table_name
select 'certain type', 'a user''s name', 1

但是如果表中已经记录了用户名,则会导致<代码>用户名列。

换句话说,如果用户名没有出现在UerName列中,我想插入一行记录。我怎样才能做到这一点?

I want to insert records into a table:

UserTypeUserNameValid
Type1Name1True

Currently I am using the following sql code:

insert into table_name
select 'certain type', 'a user''s name', 1

but if a user's name has been recorded in the table, that will cause duplicated names in UserName column.

In other words, I want to insert a row of record if a user's name does not show up in the UerName column. How can I achieve that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

帅冕 2025-01-20 03:22:55

如果我理解正确的话,您希望在表的列中强制执行唯一值。

在这种情况下,您可以对列使用 unique 约束,或者如果是 MSSQL ( T-SQL)你可以这样做:

IF NOT EXISTS(SELECT TOP 1 1 FROM table_name WHERE column_name='a user''s name') BEGIN
   INSERT INTO table_name (UserType, UserName, VALID) VALUES ('certain type', 'a user''s name', 1)
END

If i understood you correctly you want to enforce unique values within column in a table.

In that case you can either use unique constraint on a column, or if that's MSSQL (T-SQL) you can do something like this:

IF NOT EXISTS(SELECT TOP 1 1 FROM table_name WHERE column_name='a user''s name') BEGIN
   INSERT INTO table_name (UserType, UserName, VALID) VALUES ('certain type', 'a user''s name', 1)
END
娇纵 2025-01-20 03:22:55

您可以添加不存在条件:

insert into t(usertype, username, valid)
select *
from (values
    ('type1', 'name1', 1),
    ('type2', 'name2', 2)
) as to_insert(usertype, username, valid)
where not exists (
    select 1
    from t
    where t.username = to_insert.username
)

You can add a not exists condition:

insert into t(usertype, username, valid)
select *
from (values
    ('type1', 'name1', 1),
    ('type2', 'name2', 2)
) as to_insert(usertype, username, valid)
where not exists (
    select 1
    from t
    where t.username = to_insert.username
)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文