创建表时 SQL 语法错误

发布于 2024-09-19 03:59:02 字数 462 浏览 3 评论 0 原文

我最近开始学习 SQL,我无法确定是什么导致了我的语法错误(见下文):

CREATE TABLE Users(
    user_id smallint not null auto_increment,
    username varchar(50) unique,
    password varchar(41),
    dob date,
    session_id varchar not null,
    cookie varchar not null,
    PRIMARY KEY(user_id),
    CONSTRAINT dob_valid CHECK(dob < current_date())
);

当所有 varchar 字段都有预定义的长度时,这确实有效。所有 varchar 类型的字段都需要大小参数吗?

如果这个问题看起来很简单,我很抱歉。

感谢您提前的帮助

I have recently started learning SQL, I can't determine what is causing my syntax error (see below):

CREATE TABLE Users(
    user_id smallint not null auto_increment,
    username varchar(50) unique,
    password varchar(41),
    dob date,
    session_id varchar not null,
    cookie varchar not null,
    PRIMARY KEY(user_id),
    CONSTRAINT dob_valid CHECK(dob < current_date())
);

This does work when all varchar fields have a predefined length. Do all fields of type varchar require a size parameter?

I am sorry if this problem seems very simple.

Thanks for your help in advance

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

∞琼窗梦回ˉ 2024-09-26 03:59:02

是的,所有 varchar 都需要最大大小。

yes all varchar require a max size.

水溶 2024-09-26 03:59:02

正如文档所说,

CHAR 和 VARCHAR 类型是
声明的长度表明
您的最大字符数
想要存储。

检查此问题的另一种方法(长度不是可选):检查 data_type 产品.com/doc/refman/5.4/en/create-table.html" rel="nofollow noreferrer">syntax (用于 CREATE TABLE),您将看到部分内容:

 VARCHAR(length)
      [CHARACTER SET charset_name] [COLLATE collation_name]

看?在此语法描述中,(length) 部分不在方括号内:这意味着它不是可选,而是强制的(CHARACTER SETCOLLATE 部分是可选的,因此它们位于方括号内)。

我正在详细解释这种阅读文档的技术,因为,虽然学习这个非常具体的用例的具体语法当然很重要,但学习阅读手册并以非常详细的方式找到问题的答案(语法和其他)快速的方式更为重要,它将极大地提高您的 SQL 生产力。

As the docs say,

The CHAR and VARCHAR types are
declared with a length that indicates
the maximum number of characters you
want to store.

Another way of checking this (that the length is not optional): check the data_type production in the relevant docs's page on syntax (for CREATE TABLE) and you'll see, in part:

 VARCHAR(length)
      [CHARACTER SET charset_name] [COLLATE collation_name]

See? the (length) part is not within square brackets in this syntax description: that means it's not optional, but mandatory (the CHARACTER SET and COLLATE parts are optional, so they're within square brackets).

I'm explaining this technique for reading the docs at length, because, while learning the specific syntax for this very specific use case is of course important, learning to read the manuals and find answers to your questions (syntax and otherwise) in a very speedy manner is even more important, and will increase your SQL productivity enormously.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文