sql创建表的条件是两列的值不能相等

7nbnzgx9  于 2021-06-20  发布在  Mysql
关注(0)|答案(3)|浏览(332)

这个问题在这里已经有答案了

mysql中的check约束不起作用(8个答案)
基于另一列的列约束(1个答案)
两年前关门了。
如何在CREATETABLE语句中编写一个条件,说明两列不能相等?

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

);
wecizke3

wecizke31#

你会使用 check 约束条件:

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

vc9ivgsu2#

你需要 check 约束条件:

constraint chk_sendId_receiveId check (sendId <> receiveId)
azpvetkf

azpvetkf3#

使用检查约束:

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)

相关问题