sql create table,条件是2列不能具有相等的值

时间:2018-08-30 10:39:57

标签: mysql sql check-constraints

如何在create table语句中写条件说2列不能相等?

CREATE table Example(
    sendId integer,
    recieveId integer,
    **!sendId cannot equal recieveId**

);

3 个答案:

答案 0 :(得分:1)

您将使用check约束:

create table Example (
    sendId integer,
    receiveId integer,
    constraint chk_example_sendId_receiveId check (sendId <> receiveId)
);

答案 1 :(得分:1)

使用检查约束:

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)

答案 2 :(得分:0)

您需要check约束:

constraint chk_sendId_receiveId check (sendId <> receiveId)