【问题标题】:MySQL INDEX() syntax equivalent in SQL ServerSQL Server 中的 MySQL INDEX() 语法等效
【发布时间】:2019-07-02 22:30:04
【问题描述】:

我正在关注一个 PHP 工作簿,其中一个练习要求我使用以下 MySQL 代码创建一个包含列的表

CREATE TABLE messages ( 
    message_id INT UNSIGNED NOT NULL AUTO_INCREMENT, 
    parent_id INT UNSIGNED NOT NULL DEFAULT 0, 
    forum_id TINYINT UNSIGNED NOT NULL, 
    user_id MEDIUMINT UNSIGNED NOT NULL, 
    subject VARCHAR(100) NOT NULL,
    body LONGTEXT NOT NULL, 
    date_entered DATETIME NOT NULL, 
    PRIMARY KEY (message_id), 
    INDEX (parent_id), 
    INDEX (forum_id),
    INDEX (user_id),
    INDEX (date_entered) 
);

问题出在我工作的地方,他们使用 Microsoft SQL Server,因此语法不同。

我可以使用的等效 SQL Server 语法是什么

INDEX (parent_id), 
INDEX (forum_id),
INDEX (user_id),
INDEX (date_entered)

【问题讨论】:

  • 你有错误吗?显示确切的错误信息
  • 是的,我得到Incorrect syntax near 'INDEX'. If this is intended as a part of a table hint, A WITH keyword and parenthesis are now required. See SQL Server Books Online for proper syntax.
  • 当涉及到 RDBMS 供应商之间的不一致时,您遇到了冰山一角。

标签: mysql sql sql-server indexing syntax


【解决方案1】:

我可以使用的等效 SQL Server 语法是什么

 INDEX (parent_id), 
 INDEX (forum_id),
 INDEX (user_id),
 INDEX (date_entered)

查看manual 我注意到BNF 形式。

<column_index> ::=   
 INDEX index_name [ CLUSTERED | NONCLUSTERED ]  
    [ WITH ( <index_option> [ ,... n ] ) ]  
    [ ON { partition_scheme_name (column_name )   
         | filegroup_name  
         | default   
         }  
    ]   
    [ FILESTREAM_ON { filestream_filegroup_name | partition_scheme_name | "NULL" } ]  

所以 SQL Server 2008+ 也应该支持CREATE TABLE 语句中的INDEX 关键字..

但是INDEX 关键字的有效语法是使用

CREATE TABLE test ( 
   id INT
 , INDEX index_name (id)
);

但是还有其他错误,例如数据类型或关键字..

SQL server 的正确 SQL 代码是

CREATE TABLE messages ( 
 message_id INT identity(1, 1), 
 parent_id INT NOT NULL DEFAULT 0, 
 forum_id TINYINT NOT NULL, 
 user_id INT NOT NULL, 
 subject VARCHAR(100) NOT NULL,
 body TEXT NOT NULL, 
 date_entered DATETIME NOT NULL, 
 PRIMARY KEY (message_id), 
 INDEX parent_id (parent_id), 
 INDEX forum_id (forum_id),
 INDEX user_id (user_id),
 INDEX date_entered (date_entered) 
);

【讨论】:

  • 对于message_id 仍然需要identity
  • “仍然需要 message_id 的身份”确实@JoelCoehoorn 谢谢忘记那个。
【解决方案2】:

您可以使用适用于任何 SQL 引擎的语法,例如

CREATE TABLE messages ( 
    message_id INT, 
    parent_id INT NOT NULL DEFAULT 0, 
    forum_id TINYINT NOT NULL, 
    user_id INT NOT NULL, 
    subject VARCHAR(100) NOT NULL,
    body TEXT NOT NULL, 
    date_entered DATETIME NOT NULL, 
    PRIMARY KEY (message_id)
)

然后单独创建其他索引:

CREATE INDEX parent_id_idx ON messages (parent_id))

等等。

所有 SQL 引擎都应该支持这种语法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-18
    • 1970-01-01
    • 1970-01-01
    • 2014-07-14
    • 2016-08-02
    • 1970-01-01
    • 2012-02-19
    相关资源
    最近更新 更多