SQL表自引用查询与使用校验和的唯一约束
我想更好地了解在插入之前使用 CHECKSUM(具有唯一约束) 与自引用表 语句(如下所示)之间检查记录中的唯一性的差异。 在什么情况下,一种选择会成为优于另一种选择的最佳选择,原因是什么?
要求:每组列对于表中的每条记录都需要是唯一的,这就是我把这个语句放在一起的原因; 在一次数据库调用中检查所有列。
INSERT INTO tblTable
(Column1, Column2, Column3, Column4, Column5, Column6)
SELECT
@Column1, @Column2, @Column3, @Column4, @Column5, @Column6
WHERE NOT EXISTS
(SELECT DISTINCT
t1.Column1,
t1.Column2,
t2.Column3,
t2.Column4,
t3.Column5,
t3.Column6
FROM tblTable t1
JOIN tblTable t2 ON (t1.UID = t2.UID)
JOIN tblTable t3 ON (t1.UID = t3.UID)
WHERE
t1.Column1 = @Column1 and
t1.Column2 = @Column2 and
t2.Column3 = @Column3 and
t2.Column4 = @Column4 and
t3.Column5 = @Column5 and
t3.Column6 = @Column6)
I would like to better understand the differences for checking uniqueness in a record before an INSERT between using CHECKSUM (with unique constraints) versus self-referencing table statement like the one below. What scenarios would pose one option to be the best choice over the other, and for what reasons?
Requirement: Each set of columns need to be unique from every record in the table, which is why I put this statement together; to check for all columns in one call to the database.
INSERT INTO tblTable
(Column1, Column2, Column3, Column4, Column5, Column6)
SELECT
@Column1, @Column2, @Column3, @Column4, @Column5, @Column6
WHERE NOT EXISTS
(SELECT DISTINCT
t1.Column1,
t1.Column2,
t2.Column3,
t2.Column4,
t3.Column5,
t3.Column6
FROM tblTable t1
JOIN tblTable t2 ON (t1.UID = t2.UID)
JOIN tblTable t3 ON (t1.UID = t3.UID)
WHERE
t1.Column1 = @Column1 and
t1.Column2 = @Column2 and
t2.Column3 = @Column3 and
t2.Column4 = @Column4 and
t3.Column5 = @Column5 and
t3.Column6 = @Column6)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为什么您需要的不仅仅是这个 NOT EXISTS 子句?
严重地。
我从来没有想过......但自连接意味着对多于一行的唯一检查(或在一组行上唯一?或在父/子行上唯一?)。 这将使唯一行概念无效...
编辑,第二次阅读
只需使用 标准唯一约束。
不需要 CHECKSUM,无论如何它都不能保证唯一性。
Why would you need more than this NOT EXISTS clause?
Seriously.
I've never thought it through... but the self join implies unique checks over more than one row (or unique over a group of rows? or unique over parent/child rows?). Which would invalidate the unique row concept...
Edit, on 2nd reading
Just use a standard unique constraint.
No need for CHECKSUM, which does not guarantee uniqueness anyway.
使用唯一约束将保证受约束的数据是唯一的,无论其如何插入(从查询编辑器手动插入、通过存储过程、通过 ORM 工具或任何其他抽象层)。 它并不依赖于开发人员记住检查他们编写的每个查询是否违反了该原则。 它还使您的查询不那么复杂且易于阅读。 没有犯错的机会。
Using a Unique constraint will guarantee that the constrained data is unique regardless of how it is inserted (by hand from query editor, via a stored procedure, via an ORM tool or any other layer of abstraction). It doesn't rely on developers remembering to check with every query they write that they aren't violating the principle. It also makes your queries less convoluted and easy to read. No chance of mistakes.