1

Does anybody know what is wrong in this MYSQL 5.0 syntax?

CREATE TABLE IF NOT EXISTS target (
  _id int(11) NOT NULL AUTO_INCREMENT,
  time timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  map_id int(11) DEFAULT NULL,
  left int(11) DEFAULT NULL,
  top int(11) DEFAULT NULL,
  status tinyint(1) NOT NULL,
  temperature int(11) DEFAULT NULL,
  humidity float DEFAULT NULL,
  lum int(11) DEFAULT NULL,
  PRIMARY KEY (_id),
  FOREIGN KEY (map_id) REFERENCES map(id) ON DELETE CASCADE
)

I'll show you the error:

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 'left INTEGER DEFAULT NULL, top INTEGER DEFAULT NULL, status tinyint(1) NOT' at line 5

Peladao
  • 4,036
  • 1
  • 23
  • 43
Aerox
  • 669
  • 1
  • 13
  • 28
  • possible duplicate of [How can I write SQL for a table that shares the same name as a protected keyword in MySql?](http://stackoverflow.com/questions/10706920/how-can-i-write-sql-for-a-table-that-shares-the-same-name-as-a-protected-keyword) – Jocelyn May 06 '13 at 06:39

3 Answers3

2

Because left is a MySQL 5.0 reserved word. Also, even though you can escape the field name, it's never a great idea to use reserved words in a table definition.

WWW
  • 9,734
  • 1
  • 29
  • 33
2

you must write it like this:

CREATE TABLE IF NOT EXISTS target (
  _id int(11) NOT NULL AUTO_INCREMENT,
  time timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  map_id int(11) DEFAULT NULL,
  `left` int(11) DEFAULT NULL,
  top int(11) DEFAULT NULL,
  status tinyint(1) NOT NULL,
  temperature int(11) DEFAULT NULL,
  humidity float DEFAULT NULL,
  lum int(11) DEFAULT NULL,
  PRIMARY KEY (_id),
  FOREIGN KEY (map_id) REFERENCES map(id) ON DELETE CASCADE
)

look at the `` (backticks) characters in left row !

macjohn
  • 1,755
  • 14
  • 18
0

You're using reserved words as field names. You can do that, but then you have to properly escape them, like this:

CREATE TABLE IF NOT EXISTS target (
  `_id` int(11) NOT NULL AUTO_INCREMENT,
  `time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `map_id` int(11) DEFAULT NULL,
  `left` int(11) DEFAULT NULL,
  `top` int(11) DEFAULT NULL,
  `status` tinyint(1) NOT NULL,
  `temperature` int(11) DEFAULT NULL,
  `humidity` decimal(13,2) DEFAULT NULL,
  `lum` int(11) DEFAULT NULL,
  PRIMARY KEY (_id),
  FOREIGN KEY (map_id) REFERENCES map(id) ON DELETE CASCADE
)

My advise would be to avoid reserved names.

Bjoern
  • 15,934
  • 4
  • 43
  • 48