SQL约束:日期A在日期B之前-如何? [英] SQL Constraint: date A is before date B -- How?

查看:207
本文介绍了SQL约束:日期A在日期B之前-如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个需要字段 from = date to = date 的SQL表,但是我想做一个约束,以便 to 不能在 from 之前。我的程序将对其进行检查,但我想学习如何使用SQL进行实施。
我以前写过SQL,但从未真正使用过约束,也不知道它们如何工作。

I'm creating an SQL table that needs the fields from=date and to=date but I'd like to make a constraint so that to cannot be before from. My program will check for it but I'd like to learn how to enforce it with SQL. I've written SQL before but never really used constraints and don't know how they work.

所以问题是:使用标准SQL,如何确定 From To 之前?

So the question is: Using standard SQL, how do I make sure that From is before To?

推荐答案

create table foo
(
   from_date date,
   to_date date,
   constraint check_dates check (from_date < to_date)
);

或者如果需要将其应用于现有表,请使用:

Or if you need to apply this to an existing table, use:

alter table foo
   add constraint check_dates check (from_date < to_date);

PostgreSQL手册中有一章很好地介绍了检查约束: http://www.postgresql.org/docs/current/static/ddl-constraints.html#AEN2410

The PostgreSQL manual contains a good chapter about check constraints: http://www.postgresql.org/docs/current/static/ddl-constraints.html#AEN2410

这篇关于SQL约束:日期A在日期B之前-如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆