2014-10-26 108 views
11

我正在尝试在MySQL中创建一个序列(我对整个SQL非常陌生)。我正在使用以下代码,但它会导致错误:如何在MySQL中创建序列?

CREATE SEQUENCE ORDID INCREMENT BY 1 START WITH 622; 

ORDID引用我正在使用的表中的字段。如何正确创建序列?

编辑:

据称,MySQL不使用序列。我现在使用下面的代码,但是这也导致了错误。我如何解决它们?

CREATE TABLE ORD (
ORDID NUMERIC(4) NOT NULL AUTO_INCREMENT START WITH 622, 
//Rest of table code 

编辑:

我想我找到了解决。对于phpMyAdmin(我正在使用),您可以使用下面的代码。

ALTER TABLE ORD AUTO_INCREMENT = 622; 

我不知道为什么它喜欢这个,但如果其他人需要帮助,然后在这里,你去。 :)

+0

MySQL中没有这样的事情。你想做什么? – Barmar 2014-10-26 21:46:50

+0

在MySQL中,您使用具有'AUTO_INCREMENT'属性的列。 – Barmar 2014-10-26 21:47:57

+0

MySQL不支持序列 – 2014-10-26 21:54:29

回答

15

退房this article。我相信它应该可以帮助你得到你想要的东西。如果你的表已经存在,并且它已经有数据,那么你得到的错误可能是由于auto_increment尝试为其他记录分配一个已经存在的值。

总之,正如其他人已经在评论中提到的那样,序列在Oracle中不存在,因为它们在Oracle中被认为和处理。不过,你可能会使用auto_increment来完成你想要的。

没有关于具体错误的额外细节,很难提供更具体的帮助。

UPDATE

CREATE TABLE ORD (
    ORDID INT NOT NULL AUTO_INCREMENT, 
    //Rest of table code 
    PRIMARY KEY (ordid) 
) 
AUTO_INCREMENT = 622; 

This link也是用于描述AUTO_INCREMENT的使用有所帮助。 设置AUTO_INCREMENT值似乎是table option,而不是专门指定为列属性的东西。

另外,通过上面的链接,您可以通过对表格的更改设置自动增量开始值。

ALTER TABLE ORD AUTO_INCREMENT = 622; 

更新2 这里是一个working sqlfiddle example的链接,使用自动递增。
我希望这个信息可以帮助。

+0

感谢您的帮助,但现在MySQL声称此代码包含“不正确的列说明符”。 – Ben 2014-10-26 22:23:10

+0

我每次都使用大量代码从头开始创建表(如果出现问题,我将删除表并重新开始)。 MySQL从未遇到过“数字(4)”的问题。 – Ben 2014-10-26 22:31:15

+0

无视我之前的评论。我删除了它,因为它不正确。 – Daileyo 2014-10-26 22:37:08

17

这是一个解决方案suggested by the MySQl manual

If expr is given as an argument to LAST_INSERT_ID(), the value of the argument is returned by the function and is remembered as the next value to be returned by LAST_INSERT_ID(). This can be used to simulate sequences:

Create a table to hold the sequence counter and initialize it:

mysql> CREATE TABLE sequence (id INT NOT NULL); 
    mysql> INSERT INTO sequence VALUES (0); 

Use the table to generate sequence numbers like this:

mysql> UPDATE sequence SET id=LAST_INSERT_ID(id+1); 
    mysql> SELECT LAST_INSERT_ID(); 

The UPDATE statement increments the sequence counter and causes the next call to LAST_INSERT_ID() to return the updated value. The SELECT statement retrieves that value. The mysql_insert_id() C API function can also be used to get the value. See Section 23.8.7.37, “mysql_insert_id()”.

You can generate sequences without calling LAST_INSERT_ID(), but the utility of using the function this way is that the ID value is maintained in the server as the last automatically generated value. It is multi-user safe because multiple clients can issue the UPDATE statement and get their own sequence value with the SELECT statement (or mysql_insert_id()), without affecting or being affected by other clients that generate their own sequence values.