2015-08-20 203 views
1

我想在下表中插入新行:MYSQL INSERT INTO語法錯誤

+-------------------+---------------------+------+-----+---------+-------+ 
| Field    | Type    | Null | Key | Default | Extra | 
+-------------------+---------------------+------+-----+---------+-------+ 
| index    | bigint(20) unsigned | NO | PRI | NULL |  | 
| exports_fields_id | bigint(20) unsigned | NO | PRI | NULL |  | 
| exports_id  | bigint(20) unsigned | NO | MUL | NULL |  | 
+-------------------+---------------------+------+-----+---------+-------+ 

爲此我嘗試以下SQL語句:

INSERT INTO 'exports_has_export_fields' ('index', 'exports_fields_id', 'exports_id') VALUES (0, 78, 3); 

但後來我得到以下錯誤:

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 ''exports_has_export_fields' ('index', 'exports_fields_id', 'exports_id') VALUES ' at line 1

+1

使用'而不是'。 –

回答

3

您使用單引號,但你需要反引號(')來引用字段或表的名字可以與MySQL衝突保留關鍵字。

在這種情況下,只有index是保留的,即使您爲了安全起見可能會反照一切。

所以,你可以說:

INSERT INTO `exports_has_export_fields` (`index`, `exports_fields_id`, `exports_id`) VALUES (0, 78, 3); 
      ^      ^^ ^^    ^^  ^

或只是

INSERT INTO exports_has_export_fields (`index`, exports_fields_id, exports_id) VALUES (0, 78, 3); 
            ^ ^ 

When to use single quotes, double quotes, and backticks?

Backticks are to be used for table and column identifiers, but are only necessary when the identifier is a MySQL reserved keyword , or when the identifier contains whitespace characters or characters beyond a limited set (see below) It is often recommended to avoid using reserved keywords as column or table identifiers when possible, avoiding the quoting issue.

1

與(編輯與反引號)

試試吧
INSERT INTO `exports_has_export_fields` (`index`, `exports_fields_id`, `exports_id`) VALUES (0, 78, 3); 

表名和列名不應該有單引號。

如果插入一個表格,你可以縮短這樣的INSERT語句中的所有列:

INSERT INTO exports_has_export_fields VALUES (0, 78, 3); 
+0

感謝您對簡短陳述的回答。上面的那個也失敗了。只有簡短語句插入一個新行。你知道它失敗了嗎? – Bene

+0

@ user3205343:使用上面答案中提到的反引號進行嘗試。 –

+0

這不起作用,因爲'index'是MySQL中的保留關鍵字。 – fedorqui

1

你有沒有嘗試刪除從你的表名和字段中的單引號?

INSERT INTO exports_has_export_fields (`index`, exports_fields_id, exports_id) VALUES (0, 78, 3); 

或者,如果你想縮短您的查詢,儘量

INSERT INTO exports_has_export_fields VALUES (0, 78, 3); 
1

indexreserved word。引用它(帶反引號)。

所以你應該使用反引號quotes而不是單引號'。

INSERT INTO `exports_has_export_fields` (`index`, `exports_fields_id`, `exports_id`) VALUES (0, 78, 3); 
1

我覺得領域index是主鍵,它不是零 嘗試

SET sql_mode='NO_AUTO_VALUE_ON_ZERO'; 

插入0值之前。