sql 创建 table 条件是 2 列不能有相同的值
sql create table with condition that 2 columns cannot have equal values
如何在 create table 语句中编写条件来说明 2 列不能相等?
CREATE table Example(
sendId integer,
recieveId integer,
**!sendId cannot equal recieveId**
);
您将使用 check
约束:
create table Example (
sendId integer,
receiveId integer,
constraint chk_example_sendId_receiveId check (sendId <> receiveId)
);
使用检查约束:
CREATE table Example(
sendId integer,
recieveId integer,
constraint not_equal check (sendid <> recieveId)
);
由于您的列允许空值,因此您可能也需要注意这一点:
CREATE table Example(
sendId integer,
recieveId integer,
constraint not_equal check (coalesce(sendid,0) <> coalesce(recieveId,0))
);
将 NULL
视为 0
也许使用一个永远不会出现的不同值可能更合适。
根据您的 DBMS 产品,您还可以使用标准运算符 is distinct from
constraint not_equal check (sendid is distinct from receiveid)
您需要 check
约束条件:
constraint chk_sendId_receiveId check (sendId <> receiveId)
如何在 create table 语句中编写条件来说明 2 列不能相等?
CREATE table Example(
sendId integer,
recieveId integer,
**!sendId cannot equal recieveId**
);
您将使用 check
约束:
create table Example (
sendId integer,
receiveId integer,
constraint chk_example_sendId_receiveId check (sendId <> receiveId)
);
使用检查约束:
CREATE table Example(
sendId integer,
recieveId integer,
constraint not_equal check (sendid <> recieveId)
);
由于您的列允许空值,因此您可能也需要注意这一点:
CREATE table Example(
sendId integer,
recieveId integer,
constraint not_equal check (coalesce(sendid,0) <> coalesce(recieveId,0))
);
将 NULL
视为 0
也许使用一个永远不会出现的不同值可能更合适。
根据您的 DBMS 产品,您还可以使用标准运算符 is distinct from
constraint not_equal check (sendid is distinct from receiveid)
您需要 check
约束条件:
constraint chk_sendId_receiveId check (sendId <> receiveId)