How can I avoid getting this MySQL error Incorrect column specifier for column topic_id ?
MySQL Error…
#1063 - Incorrect column specifier for column 'topic_id'
SQL Schema…
CREATE TABLE discussion_topics (
topic_id char(36) NOT NULL AUTO_INCREMENT,
project_id char(36) NOT NULL,
topic_subject VARCHAR(255) NOT NULL,
topic_content TEXT default NULL,
date_created DATETIME NOT NULL,
date_last_post DATETIME NOT NULL,
created_by_user_id char(36) NOT NULL,
last_post_user_id char(36) NOT NULL,
posts_count char(36) default NULL,
PRIMARY KEY (topic_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
Mureinik
290k52 gold badges300 silver badges337 bronze badges
asked Oct 1, 2014 at 5:52
JasonDavisJasonDavis
47.7k98 gold badges311 silver badges528 bronze badges
0
To use AUTO_INCREMENT
you need to deifne column as INT
or floating-point types, not CHAR
.
AUTO_INCREMENT
use only unsigned value, so it’s good to use UNSIGNED
as well;
CREATE TABLE discussion_topics (
topic_id INT NOT NULL unsigned AUTO_INCREMENT,
project_id char(36) NOT NULL,
topic_subject VARCHAR(255) NOT NULL,
topic_content TEXT default NULL,
date_created DATETIME NOT NULL,
date_last_post DATETIME NOT NULL,
created_by_user_id char(36) NOT NULL,
last_post_user_id char(36) NOT NULL,
posts_count char(36) default NULL,
PRIMARY KEY (topic_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
Barmar
718k53 gold badges481 silver badges598 bronze badges
answered Oct 1, 2014 at 5:57
3
The auto_increment
property only works for numeric columns (integer and floating point), not char
columns:
CREATE TABLE discussion_topics (
topic_id INT NOT NULL AUTO_INCREMENT,
project_id char(36) NOT NULL,
topic_subject VARCHAR(255) NOT NULL,
topic_content TEXT default NULL,
date_created DATETIME NOT NULL,
date_last_post DATETIME NOT NULL,
created_by_user_id char(36) NOT NULL,
last_post_user_id char(36) NOT NULL,
posts_count char(36) default NULL,
PRIMARY KEY (topic_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
answered Oct 1, 2014 at 5:57
MureinikMureinik
290k52 gold badges300 silver badges337 bronze badges
Quoting the doc:
Some attributes do not apply to all data types.
AUTO_INCREMENT
applies
only to integer and floating-point types.DEFAULT
does not apply to
theBLOB
orTEXT
types.
In your case, you’re trying to apply AUTO_INCREMENT
modifier to char
column. To solve this, either drop AUTO_INCREMENT
altogether (that means you’ll have to generate a unique id on the application level) or just change topic_id
type to the relevant integer one.
As a sidenote, it makes little sense using char(36)
to store the posts count, so that column’s type probably has to be changed as well. It looks like you’re going this way to prevent integer overflow — but if you’re dealing with more than 18446744073709551615
posts (the biggest number that can be stored in BIGINT UNSIGNED
column) in a single topic, you have far bigger problem on your side probably. )
answered Oct 1, 2014 at 5:57
raina77owraina77ow
102k14 gold badges193 silver badges227 bronze badges
1
You cannot auto increment the char
values. It should be int
or long
(integers or floating points).
Try with this,
CREATE TABLE discussion_topics (
topic_id int(5) NOT NULL AUTO_INCREMENT,
project_id char(36) NOT NULL,
topic_subject VARCHAR(255) NOT NULL,
topic_content TEXT default NULL,
date_created DATETIME NOT NULL,
date_last_post DATETIME NOT NULL,
created_by_user_id char(36) NOT NULL,
last_post_user_id char(36) NOT NULL,
posts_count char(36) default NULL,
PRIMARY KEY (`topic_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
Hope this helps
answered Oct 1, 2014 at 6:05
codebotcodebot
2,5022 gold badges35 silver badges83 bronze badges
1
I was having the same problem, but using Long type. I changed for INT and it worked for me.
CREATE TABLE lists (
id INT NOT NULL AUTO_INCREMENT,
desc varchar(30),
owner varchar(20),
visibility boolean,
PRIMARY KEY (id)
);
answered Jul 28, 2016 at 9:22
J CJ C
7217 silver badges11 bronze badges
Вопрос:
Как я могу избежать получения этой ошибки MySQL Неверный спецификатор столбца для столбца topic_id?
Ошибка MySQL…
#1063 - Incorrect column specifier for column 'topic_id'
Схема SQL…
CREATE TABLE discussion_topics (
topic_id char(36) NOT NULL AUTO_INCREMENT,
project_id char(36) NOT NULL,
topic_subject VARCHAR(255) NOT NULL,
topic_content TEXT default NULL,
date_created DATETIME NOT NULL,
date_last_post DATETIME NOT NULL,
created_by_user_id char(36) NOT NULL,
last_post_user_id char(36) NOT NULL,
posts_count char(36) default NULL,
PRIMARY KEY (topic_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
Лучший ответ:
Чтобы использовать AUTO_INCREMENT
, вам нужно использовать deifne column как INT
или типы с плавающей запятой, а не CHAR
.
AUTO_INCREMENT
используйте только значение без знака, поэтому хорошо использовать UNSIGNED
,
CREATE TABLE discussion_topics (
topic_id INT NOT NULL unsigned AUTO_INCREMENT,
project_id char(36) NOT NULL,
topic_subject VARCHAR(255) NOT NULL,
topic_content TEXT default NULL,
date_created DATETIME NOT NULL,
date_last_post DATETIME NOT NULL,
created_by_user_id char(36) NOT NULL,
last_post_user_id char(36) NOT NULL,
posts_count char(36) default NULL,
PRIMARY KEY (topic_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
Ответ №1
Свойство auto_increment
работает только для числовых столбцов (целых и с плавающей запятой), а не char
:
CREATE TABLE discussion_topics (
topic_id INT NOT NULL AUTO_INCREMENT,
project_id char(36) NOT NULL,
topic_subject VARCHAR(255) NOT NULL,
topic_content TEXT default NULL,
date_created DATETIME NOT NULL,
date_last_post DATETIME NOT NULL,
created_by_user_id char(36) NOT NULL,
last_post_user_id char(36) NOT NULL,
posts_count char(36) default NULL,
PRIMARY KEY (topic_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
Ответ №2
Цитирование doc:
Некоторые атрибуты не относятся ко всем типам данных.
AUTO_INCREMENT
применяется только для целых чисел и типов с плавающей точкой.DEFAULT
не применяется к типыBLOB
илиTEXT
.
В вашем случае вы пытаетесь применить модификатор AUTO_INCREMENT
к столбцу char
. Чтобы решить эту проблему, либо полностью отбросьте AUTO_INCREMENT
(это означает, что вам нужно будет создать уникальный идентификатор на уровне приложения), либо просто измените тип topic_id
на соответствующий целочисленный.
В качестве побочного элемента мало смысла использовать char(36)
для хранения счетчиков сообщений, поэтому, вероятно, необходимо изменить тип столбца. Похоже, вы идете таким образом, чтобы предотвратить переполнение целых чисел, но если вы имеете дело с более чем 18446744073709551615
сообщениями (наибольшее число, которое может быть сохранено в столбце BIGINT UNSIGNED
) в одной теме, у вас гораздо больше проблема на вашей стороне, вероятно. )
Ответ №3
Вы не можете автоматически увеличивать значения char
. Он должен быть int
или long
(целые числа или плавающие точки).
Попробуйте с этим,
CREATE TABLE discussion_topics (
topic_id int(5) NOT NULL AUTO_INCREMENT,
project_id char(36) NOT NULL,
topic_subject VARCHAR(255) NOT NULL,
topic_content TEXT default NULL,
date_created DATETIME NOT NULL,
date_last_post DATETIME NOT NULL,
created_by_user_id char(36) NOT NULL,
last_post_user_id char(36) NOT NULL,
posts_count char(36) default NULL,
PRIMARY KEY (`topic_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
Надеюсь, что это поможет
Ответ №4
У меня была та же проблема, но с использованием типа Long. Я изменился для INT, и это сработало для меня.
CREATE TABLE lists (
id INT NOT NULL AUTO_INCREMENT,
desc varchar(30),
owner varchar(20),
visibility boolean,
PRIMARY KEY (id)
);
Ответ №5
Я также сталкиваюсь с такой же проблемой, после нескольких исследований я удаляю свой столбец id и снова делаю это с использованием типа INT. Теперь проблема решена.
Hi I need to set auto increment for a table as S1. I tried by altering the table and also by creating by new table
I am aware how to set auto_increment but when i try to set auto increment as S1 i am unable to do. since i need the primary key values should be S1,S2,S3 as following records. can any one please suggest the data type for that,
desc test_1;
+-------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| id | varchar(10) | NO | PRI | NULL | |
| name | varchar(100) | NO | | NULL | |
+-------+--------------+------+-----+---------+-------+
2 rows in set (0.00 sec)
mysql> ALTER TABLE test_1 AUTO_INCREMENT='S1';
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''S1'' at line 1
mysql> create table tbl(ID varchar(100) not null primary key auto_increment,name varchar(100)) auto_increment='s1';
ERROR 1063 (42000): Incorrect column specifier for column 'ID'
mysql> create table tbl(ID text not null primary key auto_increment,name varchar(100)) auto_increment='s1';
ERROR 1063 (42000): Incorrect column specifier for column 'ID'
mysql> create table tbl(ID varchar(100) not null primary key auto_increment,name varchar(100)) auto_increment='s';
ERROR 1063 (42000): Incorrect column specifier for column 'ID'
asked Aug 1, 2014 at 7:37
Autoincrement values can only be numeric (integer and floats types if I remember correctly).
If you want to store S1, …., S1000, just store an integer, and return the extra S on select or on client side:
create table tbl(ID bigint not null primary key auto_increment,name varchar(100)) auto_increment=1;
insert into tbl (name) values ('a');
...
select concat('S', id) as id, name from tbl;
+----+------+
| id | name |
+----+------+
| S1 | a |
| S2 | a |
| S3 | a |
| S4 | a |
...
answered Aug 1, 2014 at 7:45
jynusjynus
14.4k1 gold badge31 silver badges42 bronze badges
0
The auto increment mechanism is a feature in SQL type database that allows you to automatically generate a unique number as a value for your column when you perform an INSERT
statement.
The mechanism can be added to your MySQL table column by adding the AUTO_INCREMENT
attribute to the column definition of the CREATE TABLE
statement.
In the following example, AUTO_INCREMENT
attribute is added to the student_id
column of the students
table:
CREATE TABLE students (
student_id MEDIUMINT NOT NULL AUTO_INCREMENT,
first_name CHAR(30) NOT NULL,
PRIMARY KEY (student_id)
);
The AUTO_INCREMENT
attribute is added next to the NOT NULL
attribute in the example above.
Please note that the AUTO_INCREMENT
attribute only works for integer data type. Adding the auto increment feature to columns with other data types will cause the Incorrect column specifier
error as shown below:
mysql> CREATE TABLE students (
-> student_id CHAR(30) NOT NULL AUTO_INCREMENT,
-> first_name CHAR(30) NOT NULL,
-> PRIMARY KEY (student_id)
-> );
ERROR 1063 (42000): Incorrect column specifier for column 'student_id'
Each time you INSERT
a new value to the students
table, the student_id
column value will be incremented automatically.
Let’s execute some INSERT
statements as an example:
INSERT INTO students (first_name) VALUE ("Chris");
INSERT INTO students (first_name) VALUE ("Jack");
INSERT INTO students (first_name) VALUE ("Sarah");
Now run a SELECT
statement to retrieve the records stored in students
table.
The table content would be as follows:
+-------------+------------+
| student_id | first_name |
+-------------+------------+
| 1 | Chris |
| 2 | Jack |
| 3 | Sarah |
+-------------+------------+
As you can see, the student_id
value is automatically generated by MySQL. It starts from the number 1
and incremented by 1
each time you insert a new row.
You can also put NULL
value for the auto increment column as shown below:
INSERT INTO students (student_id, first_name) VALUE (NULL, "Helen");
The student_id
column will automatically adjust the value from NULL
to the next sequential value in your table.
You can change the initial value from 1
into any other number by adding the AUTO_INCREMENT =
syntax by the end of your CREATE TABLE
statement as shown below:
CREATE TABLE students (
student_id MEDIUMINT NOT NULL AUTO_INCREMENT,
first_name CHAR(30) NOT NULL,
PRIMARY KEY (student_id)
) AUTO_INCREMENT=1000;
Or if you already have the table, you can use the ALTER TABLE
statement to change the initial value:
ALTER TABLE students AUTO_INCREMENT = 1000;
Now run the INSERT
statements again:
INSERT INTO students (first_name) VALUE ("Eric");
INSERT INTO students (first_name) VALUE ("Anna");
INSERT INTO students (first_name) VALUE ("Mary");
This time the student_id
value will start from 1000
as you can see below:
+-------------+------------+
| student_id | first_name |
+-------------+------------+
| 1 | Chris |
| 2 | Jack |
| 3 | Sarah |
| 1000 | Eric |
| 1001 | Anna |
| 1002 | Mary |
+-------------+------------+
And that’s how you can add the AUTO_INCREMENT
attribute to a MySQL column. Next, let’s see how you can increase the increment value for each new record.
Increasing AUTO_INCREMENT incremental value
The increment value of a column with AUTO_INCREMENT
attribute is controlled by MySQL through the auto_increment_increment
global variable.
You can find the variable in your MySQL database by executing SHOW VARIABLES
query as follows:
SHOW VARIABLES LIKE 'auto_increment_increment';
By default, the auto_increment_increment
value should be 1
, which means your AUTO_INCREMENT
column value should go up by 1
each time you perform an INSERT
statement.
Here’s the result on my local server:
mysql> SHOW VARIABLES LIKE 'auto_increment_increment';
+--------------------------+-------+
| Variable_name | Value |
+--------------------------+-------+
| auto_increment_increment | 1 |
+--------------------------+-------+
1 row in set (0.01 sec)
Let’s set the auto_increment_increment
value to 10
using the SET GLOBAL VARIABLE
statement as shown below:
SET GLOBAL auto_increment_increment=10;
Now each INSERT
statement will cause the column with AUTO_INCREMENT
attribute to leap by 10
instead of 1
.
In the example below, the student_id
column jumped from 1
to 11
:
+-------------+------------+
| student_id | first_name |
+-------------+------------+
| 1 | Joan |
| 11 | Eddy |
+-------------+------------+
You’ve just learned about MySQL’s auto increment feature and how you can change the increment value by changing the auto_increment_increment
variable value. Nice work! 😉
За последние 24 часа нас посетили 8655 программистов и 538 роботов. Сейчас ищут 355 программистов …
Проблема-Некорректный определитель столбца для столбца ‘%s’
Тема в разделе «MySQL», создана пользователем Resident, 23 май 2007.
-
Resident
Активный пользователь- С нами с:
- 23 май 2007
- Сообщения:
- 3
- Симпатии:
- 0
Рад всех приветствовать!
Помогите разобраться, не могу установить базу, постоянно выдает такое сообщение:— Структура таблицы `COLUMN_PRIVILEGES`
—
CREATE TEMPORARY TABLE `COLUMN_PRIVILEGES` (`GRANTEE` varchar( 81 ) NOT NULL default »,
`TABLE_CATALOG` varchar( 512 ) default NULL ,
`TABLE_SCHEMA` varchar( 64 ) NOT NULL default »,
`TABLE_NAME` varchar( 64 ) NOT NULL default »,
`COLUMN_NAME` varchar( 64 ) NOT NULL default »,
`PRIVILEGE_TYPE` varchar( 64 ) NOT NULL default »,
`IS_GRANTABLE` varchar( 3 ) NOT NULL default »
) ENGINE = MEMORY DEFAULT CHARSET = utf8;Ответ MySQL:
Error: 1063 SQLSTATE: 42000 (ER_WRONG_FIELD_SPEC)
Message: Некорректный определитель столбца для столбца ‘%s’
——————-Пытался «default «убрать, бесполезно. Как можно исправить ошибку, может кто знает?
P.S.
Раньше база стояла на другом хостинге, все прекрастно работало, сменил хост и из трех баз одна не хочет устанавливаться. -
Resident
Сообщение об ошибке не очень информативное…
Попробуй изменить varchar(512) на varchar(255). По-моему, VARCHAR не может быть длиннее 255 символов. -
Resident
Активный пользователь- С нами с:
- 23 май 2007
- Сообщения:
- 3
- Симпатии:
- 0
Изменил на 255 , теперь другая проблема
—
— Дамп данных таблицы `COLUMN_PRIVILEGES`
—
— ———————————————————
—
— Структура таблицы `KEY_COLUMN_USAGE`
—
CREATE TEMPORARY TABLE `KEY_COLUMN_USAGE` (`CONSTRAINT_CATALOG` varchar( 512 ) default NULL ,
`CONSTRAINT_SCHEMA` varchar( 64 ) NOT NULL default »,
`CONSTRAINT_NAME` varchar( 64 ) NOT NULL default »,
`TABLE_CATALOG` varchar( 512 ) default NULL ,
`TABLE_SCHEMA` varchar( 64 ) NOT NULL default »,
`TABLE_NAME` varchar( 64 ) NOT NULL default »,
`COLUMN_NAME` varchar( 64 ) NOT NULL default »,
`ORDINAL_POSITION` bigint( 10 ) NOT NULL default ‘0’,
`POSITION_IN_UNIQUE_CONSTRAINT` bigint( 10 ) default NULL ,
`REFERENCED_TABLE_SCHEMA` varchar( 64 ) default NULL ,
`REFERENCED_TABLE_NAME` varchar( 64 ) default NULL ,
`REFERENCED_COLUMN_NAME` varchar( 64 ) default NULL
) ENGINE = MEMORY DEFAULT CHARSET = utf8;Ответ MySQL:
#1163 — The used table type doesn’t support BLOB/TEXT columns
————
Там тоже изменил на 255 и всеровно тоже самое, по всей видимости проблема не в этом. на старом хостинге ведьработало все -
Resident
Активный пользователь- С нами с:
- 23 май 2007
- Сообщения:
- 3
- Симпатии:
- 0
Не, на самом деле ты был прав, я все что там было в базе со значением 512 изменил 255 и все прекрастно импортировал. Спасибо.