前言

怎么又是这个错,感觉似曾相识之前遇到过多次了。是的这就是mysql语句报错1064 - You have an error in your SQL 。syntax;...near...感觉每次不管什么原因,都是报的类似错误呢。。。

本文旨在整理开发过程中遇到的类似的错误,并持续更新。

1.新建表时报错


1064 - 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 ') ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户作品表'' at line 15  


 建表语句如下:

CREATE TABLE `user_work`` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '自增主键',
  `is_deleted` tinyint(1) NOT NULL DEFAULT '0' COMMENT '是否删除 0-未删除 1-删除',
  `gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `gmt_modify` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改时间',
  `version` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '版本号',
  `user_name` int(2) NOT NULL,
  `sex` varchar(32) NOT NULL,
  `code` bigint(20) NOT NULL,
  `lesson_id` bigint(20) NOT NULL,
  `work_id` bigint(20) NOT NULL,
  `grade` bigint(20) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `fk_userId` (`pin`) USING BTREE,
  KEY `fk_work_id` (`lesson_time_id`) USING BTREE,
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户作业';

原因:mysql语句错误,14行末尾多了个逗号,去掉即可。

2.mysql保留关键字报错 ERROR 1064 (42000)

执行语句:

select * from answer where analyze = '真棒'

报错:


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 'analyze = '真棒'' at line 1


解决方法:
1、若使用了mysql的保留字,需要将其用反引号引起来。
mysql> select * from cfg_parameter where `analyze`='真棒';

2、项目中用的数据库插件可能是自动生成代码,简化了手写,这样的话生成的sql关键字无法带引号。建议不要在创建表的过程中使用mysql保留字,避免后期造成麻烦。

mysql保留关键字列表:

mysql保留关键字

现在使用navicat图形界面或者Hibernate做映射生成表的时候,渐渐的会忽视掉关键字这个问题,而后续也会不断的产生错误提示,一遍遍的查询代码无果,甚至开始怀疑人生,但是其实很多情况下只是使用了保留字而已,因此在设计数据库之初便要尽量的规避关键字和保留字。

但是这里要提一下的是mysql是支持使用关键字做字段名的,但是针对保留关键字是必须要加引用。mysql官网提供了三个例子是可以很好的说明这些的。

interval begin、end都是关键字,interval是保留关键字,因此会报错
mysql> CREATE TABLE interval (begin INT, end INT);
ERROR 1064 (42000): You have an error in your SQL syntax ...
near 'interval (begin INT, end INT)'

当给interval加上引用''后便可以正确执行该sql语句,也不会报begin、end的错,因为这是mysql允许的,但是不推荐这个用法,谁知道升级之后会不会变成保留字。。。。。。

mysql> CREATE TABLE `interval` (begin INT, end INT);
Query OK, 0 rows affected (0.01 sec)

(这个可以略过,,,,,反正不推荐使用关键字做这些事,)还有一种情况——内置函数的名字,官网是这样说的:

Names of built-in functions are permitted as identifiers but may require care to be used as such

mysql> CREATE TABLE mydb.interval (begin INT, end INT);
Query OK, 0 rows affected (0.01 sec)

下面是最新版的mysql的关键字和保留字的表,可以在设计时多查一查,(R)是保留关键字

有些人可能还不明白关键字和保留字的区别,简单的说,关键字分两种:非保留和保留,保留关键字又有一个特殊类别叫未来保留。

mysql5.7官方文档地址:https://dev.mysql.com/doc/refman/5.7/en/keywords.html

Table 9.2 Keywords and Reserved Words in MySQL 5.7

ACCESSIBLE (R)ACCOUNT[a]ACTION
ADD (R)AFTERAGAINST
AGGREGATEALGORITHMALL (R)
ALTER (R)ALWAYS[b]ANALYSE
ANALYZE (R)AND (R)ANY
AS (R)ASC (R)ASCII
ASENSITIVE (R)ATAUTOEXTEND_SIZE
AUTO_INCREMENTAVGAVG_ROW_LENGTH
BACKUPBEFORE (R)BEGIN
BETWEEN (R)BIGINT (R)BINARY (R)
BINLOGBITBLOB (R)
BLOCKBOOLBOOLEAN
BOTH (R)BTREEBY (R)
BYTECACHECALL (R)
CASCADE (R)CASCADEDCASE (R)
CATALOG_NAMECHAINCHANGE (R)
CHANGEDCHANNEL[c]CHAR (R)
CHARACTER (R)CHARSETCHECK (R)
CHECKSUMCIPHERCLASS_ORIGIN
CLIENTCLOSECOALESCE
CODECOLLATE (R)COLLATION
COLUMN (R)COLUMNSCOLUMN_FORMAT
COLUMN_NAMECOMMENTCOMMIT
COMMITTEDCOMPACTCOMPLETION
COMPRESSEDCOMPRESSION[d]CONCURRENT
CONDITION (R)CONNECTIONCONSISTENT
CONSTRAINT (R)CONSTRAINT_CATALOGCONSTRAINT_NAME
CONSTRAINT_SCHEMACONTAINSCONTEXT
CONTINUE (R)CONVERT (R)CPU
CREATE (R)CROSS (R)CUBE
CURRENTCURRENT_DATE (R)CURRENT_TIME (R)
CURRENT_TIMESTAMP (R)CURRENT_USER (R)CURSOR (R)
CURSOR_NAMEDATADATABASE (R)
DATABASES (R)DATAFILEDATE
DATETIMEDAYDAY_HOUR (R)
DAY_MICROSECOND (R)DAY_MINUTE (R)DAY_SECOND (R)
DEALLOCATEDEC (R)DECIMAL (R)
DECLARE (R)DEFAULT (R)DEFAULT_AUTH
DEFINERDELAYED (R)DELAY_KEY_WRITE
DELETE (R)DESC (R)DESCRIBE (R)
DES_KEY_FILEDETERMINISTIC (R)DIAGNOSTICS
DIRECTORYDISABLEDISCARD
DISKDISTINCT (R)DISTINCTROW (R)
DIV (R)DODOUBLE (R)
DROP (R)DUAL (R)DUMPFILE
DUPLICATEDYNAMICEACH (R)
ELSE (R)ELSEIF (R)ENABLE
ENCLOSED (R)ENCRYPTION[e]END
ENDSENGINEENGINES
ENUMERRORERRORS
ESCAPEESCAPED (R)EVENT
EVENTSEVERYEXCHANGE
EXECUTEEXISTS (R)EXIT (R)
EXPANSIONEXPIREEXPLAIN (R)
EXPORTEXTENDEDEXTENT_SIZE
FALSE (R)FASTFAULTS
FETCH (R)FIELDSFILE
FILE_BLOCK_SIZE[f]FILTER[g]FIRST
FIXEDFLOAT (R)FLOAT4 (R)
FLOAT8 (R)FLUSHFOLLOWS[h]
FOR (R)FORCE (R)FOREIGN (R)
FORMATFOUNDFROM (R)
FULLFULLTEXT (R)FUNCTION
GENERALGENERATED[i] (R)GEOMETRY
GEOMETRYCOLLECTIONGET (R)GET_FORMAT
GLOBALGRANT (R)GRANTS
GROUP (R)GROUP_REPLICATION[j]HANDLER
HASHHAVING (R)HELP
HIGH_PRIORITY (R)HOSTHOSTS
HOURHOUR_MICROSECOND (R)HOUR_MINUTE (R)
HOUR_SECOND (R)IDENTIFIEDIF (R)
IGNORE (R)IGNORE_SERVER_IDSIMPORT
IN (R)INDEX (R)INDEXES
INFILE (R)INITIAL_SIZEINNER (R)
INOUT (R)INSENSITIVE (R)INSERT (R)
INSERT_METHODINSTALLINSTANCE[k]
INT (R)INT1 (R)INT2 (R)
INT3 (R)INT4 (R)INT8 (R)
INTEGER (R)INTERVAL (R)INTO (R)
INVOKERIOIO_AFTER_GTIDS (R)
IO_BEFORE_GTIDS (R)IO_THREADIPC
IS (R)ISOLATIONISSUER
ITERATE (R)JOIN (R)JSON[l]
KEY (R)KEYS (R)KEY_BLOCK_SIZE
KILL (R)LANGUAGELAST
LEADING (R)LEAVE (R)LEAVES
LEFT (R)LESSLEVEL
LIKE (R)LIMIT (R)LINEAR (R)
LINES (R)LINESTRINGLIST
LOAD (R)LOCALLOCALTIME (R)
LOCALTIMESTAMP (R)LOCK (R)LOCKS
LOGFILELOGSLONG (R)
LONGBLOB (R)LONGTEXT (R)LOOP (R)
LOW_PRIORITY (R)MASTERMASTER_AUTO_POSITION
MASTER_BIND (R)MASTER_CONNECT_RETRYMASTER_DELAY
MASTER_HEARTBEAT_PERIODMASTER_HOSTMASTER_LOG_FILE
MASTER_LOG_POSMASTER_PASSWORDMASTER_PORT
MASTER_RETRY_COUNTMASTER_SERVER_IDMASTER_SSL
MASTER_SSL_CAMASTER_SSL_CAPATHMASTER_SSL_CERT
MASTER_SSL_CIPHERMASTER_SSL_CRLMASTER_SSL_CRLPATH
MASTER_SSL_KEYMASTER_SSL_VERIFY_SERVER_CERT (R)MASTER_TLS_VERSION[m]
MASTER_USERMATCH (R)MAXVALUE (R)
MAX_CONNECTIONS_PER_HOURMAX_QUERIES_PER_HOURMAX_ROWS
MAX_SIZEMAX_STATEMENT_TIME[n]MAX_UPDATES_PER_HOUR
MAX_USER_CONNECTIONSMEDIUMMEDIUMBLOB (R)
MEDIUMINT (R)MEDIUMTEXT (R)MEMORY
MERGEMESSAGE_TEXTMICROSECOND
MIDDLEINT (R)MIGRATEMINUTE
MINUTE_MICROSECOND (R)MINUTE_SECOND (R)MIN_ROWS
MOD (R)MODEMODIFIES (R)
MODIFYMONTHMULTILINESTRING
MULTIPOINTMULTIPOLYGONMUTEX
MYSQL_ERRNONAMENAMES
NATIONALNATURAL (R)NCHAR
NDBNDBCLUSTERNEVER[o]
NEWNEXTNO
NODEGROUPNONBLOCKING[p]NONE
NOT (R)NO_WAITNO_WRITE_TO_BINLOG (R)
NULL (R)NUMBERNUMERIC (R)
NVARCHAROFFSETOLD_PASSWORD[q]
ON (R)ONEONLY
OPENOPTIMIZE (R)OPTIMIZER_COSTS[r] (R)
OPTION (R)OPTIONALLY (R)OPTIONS
OR (R)ORDER (R)OUT (R)
OUTER (R)OUTFILE (R)OWNER
PACK_KEYSPAGEPARSER
PARSE_GCOL_EXPR[s]PARTIALPARTITION (R)
PARTITIONINGPARTITIONSPASSWORD
PHASEPLUGINPLUGINS
PLUGIN_DIRPOINTPOLYGON
PORTPRECEDES[t]PRECISION (R)
PREPAREPRESERVEPREV
PRIMARY (R)PRIVILEGESPROCEDURE (R)
PROCESSLISTPROFILEPROFILES
PROXYPURGE (R)QUARTER
QUERYQUICKRANGE (R)
READ (R)READS (R)READ_ONLY
READ_WRITE (R)REAL (R)REBUILD
RECOVERREDOFILEREDO_BUFFER_SIZE
REDUNDANTREFERENCES (R)REGEXP (R)
RELAYRELAYLOGRELAY_LOG_FILE
RELAY_LOG_POSRELAY_THREADRELEASE (R)
RELOADREMOVERENAME (R)
REORGANIZEREPAIRREPEAT (R)
REPEATABLEREPLACE (R)REPLICATE_DO_DB[u]
REPLICATE_DO_TABLE[v]REPLICATE_IGNORE_DB[w]REPLICATE_IGNORE_TABLE[x]
REPLICATE_REWRITE_DB[y]REPLICATE_WILD_DO_TABLE[z]REPLICATE_WILD_IGNORE_TABLE[aa]
REPLICATIONREQUIRE (R)RESET
RESIGNAL (R)RESTORERESTRICT (R)
RESUMERETURN (R)RETURNED_SQLSTATE
RETURNSREVERSEREVOKE (R)
RIGHT (R)RLIKE (R)ROLLBACK
ROLLUPROTATE[ab]ROUTINE
ROWROWSROW_COUNT
ROW_FORMATRTREESAVEPOINT
SCHEDULESCHEMA (R)SCHEMAS (R)
SCHEMA_NAMESECONDSECOND_MICROSECOND (R)
SECURITYSELECT (R)SENSITIVE (R)
SEPARATOR (R)SERIALSERIALIZABLE
SERVERSESSIONSET (R)
SHARESHOW (R)SHUTDOWN
SIGNAL (R)SIGNEDSIMPLE
SLAVESLOWSMALLINT (R)
SNAPSHOTSOCKETSOME
SONAMESOUNDSSOURCE
SPATIAL (R)SPECIFIC (R)SQL (R)
SQLEXCEPTION (R)SQLSTATE (R)SQLWARNING (R)
SQL_AFTER_GTIDSSQL_AFTER_MTS_GAPSSQL_BEFORE_GTIDS
SQL_BIG_RESULT (R)SQL_BUFFER_RESULTSQL_CACHE
SQL_CALC_FOUND_ROWS (R)SQL_NO_CACHESQL_SMALL_RESULT (R)
SQL_THREADSQL_TSI_DAYSQL_TSI_HOUR
SQL_TSI_MINUTESQL_TSI_MONTHSQL_TSI_QUARTER
SQL_TSI_SECONDSQL_TSI_WEEKSQL_TSI_YEAR
SSL (R)STACKEDSTART
STARTING (R)STARTSSTATS_AUTO_RECALC
STATS_PERSISTENTSTATS_SAMPLE_PAGESSTATUS
STOPSTORAGESTORED[ac] (R)
STRAIGHT_JOIN (R)STRINGSUBCLASS_ORIGIN
SUBJECTSUBPARTITIONSUBPARTITIONS
SUPERSUSPENDSWAPS
SWITCHESTABLE (R)TABLES
TABLESPACETABLE_CHECKSUMTABLE_NAME
TEMPORARYTEMPTABLETERMINATED (R)
TEXTTHANTHEN (R)
TIMETIMESTAMPTIMESTAMPADD
TIMESTAMPDIFFTINYBLOB (R)TINYINT (R)
TINYTEXT (R)TO (R)TRAILING (R)
TRANSACTIONTRIGGER (R)TRIGGERS
TRUE (R)TRUNCATETYPE
TYPESUNCOMMITTEDUNDEFINED
UNDO (R)UNDOFILEUNDO_BUFFER_SIZE
UNICODEUNINSTALLUNION (R)
UNIQUE (R)UNKNOWNUNLOCK (R)
UNSIGNED (R)UNTILUPDATE (R)
UPGRADEUSAGE (R)USE (R)
USERUSER_RESOURCESUSE_FRM
USING (R)UTC_DATE (R)UTC_TIME (R)
UTC_TIMESTAMP (R)VALIDATION[ad]VALUE
VALUES (R)VARBINARY (R)VARCHAR (R)
VARCHARACTER (R)VARIABLESVARYING (R)
VIEWVIRTUAL[ae] (R)WAIT
WARNINGSWEEKWEIGHT_STRING
WHEN (R)WHERE (R)WHILE (R)
WITH (R)WITHOUT[af]WORK
WRAPPERWRITE (R)X509
XAXID[ag]XML
XOR (R)YEARYEAR_MONTH (R)
ZEROFILL (R)  

[a] ACCOUNT: added in 5.7.6 (nonreserved)

[b] ALWAYS: added in 5.7.6 (nonreserved)

[c] CHANNEL: added in 5.7.6 (nonreserved)

[d] COMPRESSION: added in 5.7.8 (nonreserved)

[e] ENCRYPTION: added in 5.7.11 (nonreserved)

[f] FILE_BLOCK_SIZE: added in 5.7.6 (nonreserved)

[g] FILTER: added in 5.7.3 (nonreserved)

[h] FOLLOWS: added in 5.7.2 (nonreserved)

[i] GENERATED: added in 5.7.6 (reserved)

[j] GROUP_REPLICATION: added in 5.7.6 (nonreserved)

[k] INSTANCE: added in 5.7.11 (nonreserved)

[l] JSON: added in 5.7.8 (nonreserved)

[m] MASTER_TLS_VERSION: added in 5.7.10 (nonreserved)

[n] MAX_STATEMENT_TIME: added in 5.7.4 (nonreserved); removed in 5.7.8

[o] NEVER: added in 5.7.4 (nonreserved)

[p] NONBLOCKING: removed in 5.7.6

[q] OLD_PASSWORD: removed in 5.7.5

[r] OPTIMIZER_COSTS: added in 5.7.5 (reserved)

[s] PARSE_GCOL_EXPR: added in 5.7.6 (reserved); became nonreserved in 5.7.8

[t] PRECEDES: added in 5.7.2 (nonreserved)

[u] REPLICATE_DO_DB: added in 5.7.3 (nonreserved)

[v] REPLICATE_DO_TABLE: added in 5.7.3 (nonreserved)

[w] REPLICATE_IGNORE_DB: added in 5.7.3 (nonreserved)

[x] REPLICATE_IGNORE_TABLE: added in 5.7.3 (nonreserved)

[y] REPLICATE_REWRITE_DB: added in 5.7.3 (nonreserved)

[z] REPLICATE_WILD_DO_TABLE: added in 5.7.3 (nonreserved)

[aa] REPLICATE_WILD_IGNORE_TABLE: added in 5.7.3 (nonreserved)

[ab] ROTATE: added in 5.7.11 (nonreserved)

[ac] STORED: added in 5.7.6 (reserved)

[ad] VALIDATION: added in 5.7.5 (nonreserved)

[ae] VIRTUAL: added in 5.7.6 (reserved)

[af] WITHOUT: added in 5.7.5 (nonreserved)

[ag] XID: added in 5.7.5 (nonreserved)

5.7相比于5.6新增的关键字

ACCOUNTALWAYSCHANNEL
COMPRESSIONENCRYPTIONFILE_BLOCK_SIZE
FILTERFOLLOWSGENERATED (R)
GROUP_REPLICATIONINSTANCEJSON
MASTER_TLS_VERSIONNEVEROPTIMIZER_COSTS (R)
PARSE_GCOL_EXPRPRECEDESREPLICATE_DO_DB
REPLICATE_DO_TABLEREPLICATE_IGNORE_DBREPLICATE_IGNORE_TABLE
REPLICATE_REWRITE_DBREPLICATE_WILD_DO_TABLEREPLICATE_WILD_IGNORE_TABLE
ROTATESTACKEDSTORED (R)
VALIDATIONVIRTUAL (R)WITHOUT
XID  

5.7相比于5.6删除的关键字

OLD_PASSWORD  

参见:https://dev.mysql.com/doc/refman/5.7/en/keywords.html 

Logo

更多推荐