SQL 约束在两列中具有一个唯一值

标签 sql constraints unique multiple-columns

我需要确保一个值在两列中是唯一的(这不是“两列”索引问题)。

Table A
Column A1       Column A2

Memphis         New York     -> ok
San Francisco   Miami        -> ok
Washington      Chicago      -> ok
Miami           Las Vegas    -> Forbidden ! Miami already exists 

这可能吗?

我的例子是城市,但不要专注于此。我真正需要的是生成的十六进制 id。

最佳答案

在 SQL Server 中,可以借助索引 View 来强制执行唯一性。您还需要在与表 A 相同的数据库中提供一个数字表(如果您还没有)。

这是我的测试脚本,其中包含一些评论:

CREATE TABLE MyNumbersTable (Value int);
-- You need at least 2 rows, by the number of columns
-- you are going to implement uniqueness on
INSERT INTO MyNumbersTable
SELECT 1 UNION ALL
SELECT 2;
GO
CREATE TABLE MyUniqueCities (  -- the main table
  ID int IDENTITY,
  City1 varchar(50) NOT NULL,
  City2 varchar(50) NOT NULL
);
GO
CREATE VIEW MyIndexedView
WITH SCHEMABINDING  -- this is required for creating an indexed view
AS
SELECT
  City = CASE t.Value    -- after supplying the numbers table
    WHEN 1 THEN u.City1  -- with the necessary number of rows
    WHEN 2 THEN u.City2  -- you can extend this CASE expression
  END                    -- to add more columns to the constraint
FROM dbo.MyUniqueCities u
  INNER JOIN dbo.MyNumbersTable t
    ON t.Value BETWEEN 1 AND 2  -- change here too for more columns
GO
-- the first index on an indexed view *must* be unique,
-- which suits us perfectly
CREATE UNIQUE CLUSTERED INDEX UIX_MyIndexedView ON MyIndexedView (City)
GO
-- the first two rows insert fine
INSERT INTO MyUniqueCities VALUES ('London', 'New York');
INSERT INTO MyUniqueCities VALUES ('Amsterdam', 'Prague');
-- the following insert produces an error, because of 'London'
INSERT INTO MyUniqueCities VALUES ('Melbourne', 'London');
GO
DROP VIEW MyIndexedView
DROP TABLE MyUniqueCities
DROP TABLE MyNumbersTable
GO

有用的阅读:

关于SQL 约束在两列中具有一个唯一值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6190022/

相关文章:

php - 由数字组成的唯一ID

python - Pandas GroupBy - 仅显示具有多个独特特征值的组

powershell - 如何根据 powershell 中对象的两个属性选择唯一对象?

php - 我需要清理用于声明几何形状的字符串吗?

sql - postgres string_agg 和 GROUP BY 子句

java - 错误消息 ORA-00933 : SQL command not properly ended

swift - TableView 单元格 : Constraint change conflicts tableView. endUpdates()

ios - 在 Swift 中使用视觉格式通过约束格式化 TextView

sql - 通过查看所有列删除重复的 SQL 行

ios - 让 WKWebView 覆盖整个屏幕