Create Table Syntax Error - mysql

I received a MySQL data dump and am trying to insert the data into a set of temporary tables. The creation statement for the first table is shown below. When I run this I receive 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 ''temp_books'( 'ID'int( 11 ) NOT NULL AUTO_INCREMENT, 'start'varchar( 20 ) ' at line 1". I've checked the documentation for MySQL syntax, and I don't see that the problem is.
CREATE TABLE 'temp_books' (
'ID' int(11) NOT NULL AUTO_INCREMENT,
'start' varchar(20) NOT NULL,
'customer_id' int(11) NOT NULL DEFAULT '0',
'total_num' int(11) NOT NULL,
'amount' double(5,2) NOT NULL DEFAULT '0.00',
'changed' timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY ('ID'),
UNIQUE KEY 'start' ('start')
) ENGINE=MyISAM AUTO_INCREMENT=4853 DEFAULT CHARSET=latin1;

You shouldn't put single-quotes on your identifiers. If you're going to quote them use the "back tick" character (“`”). You can also use double-quotes but you have to specify that mode:
SET sql_mode='ANSI_QUOTES';
http://dev.mysql.com/doc/refman/5.0/en/identifiers.html

I've ALWAYS had issues with CREATE TABLE. Not sure why. Takes some trial-and-error.
Try this:
CREATE TABLE temp_books (
ID int(11) NOT NULL AUTO_INCREMENT,
start varchar(20) NOT NULL,
customer_id int(11) NOT NULL DEFAULT '0',
total_num int(11) NOT NULL,
amount double(5,2) NOT NULL DEFAULT '0.00',
changed timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (ID),
UNIQUE KEY start (start)
) ENGINE=MyISAM AUTO_INCREMENT=4853 DEFAULT CHARSET=latin1;

I had to delete the quote marks, as well as the default for the changed field, as well as the default charset. Hopefully that won't affect the data.

Here's another way of writing it that might work for some: (left away most of the columns for brevity)
create table temp_books
(
id int not null,
start varchar(255) null,
constraint six_cb_datasource_pk
primary key (id)
);

Related

Foreign key constraint fails but referenced row exists

I'm running MySQL 5.7.21 on Amazon RDS.
I know this question has been asked a thousand times, but I'm getting the issue on a scenario I wouldn't expect, so please read through before downvoting or marking as duplicate.
I'm not restoring the database, just running single INSERT queries, so is not a matter of ordering.
The referenced row does exist on the table; me and my colleagues had it triple checked.
As one might expect, disabling the FK checks with SET foreign_key_checks = 0 does make the query work.
I've seen this happening because of different table charsets, but in this case, both use utf8mb4. Also both have collation set to utf8mb4_general_ci.
This is happening in a production environment, so dropping the tables and recreating them is something I would like to avoid.
Some additional information:
The FK constraint was created AFTER the original tables were already populated.
Here is the relevant portion of the current DDL:
CREATE TABLE `VehicleTickets` (
`id` varchar(50) NOT NULL,
`vehiclePlate` char(7) NOT NULL,
`organizationId` varchar(50) NOT NULL,
`createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updatedAt` timestamp NULL DEFAULT NULL,
`status` varchar(15) NOT NULL DEFAULT 'OPEN',
`description` text NULL DEFAULT NULL,
`ticketInfo` json DEFAULT NULL,
`externalId` varchar(100) GENERATED ALWAYS AS (json_unquote(json_extract(`ticketInfo`,'$.externalId'))) VIRTUAL,
`value` decimal(10,2) GENERATED ALWAYS AS (json_unquote(json_extract(`ticketInfo`,'$.value'))) VIRTUAL,
`issuedAt` timestamp GENERATED ALWAYS AS (json_unquote(json_extract(`ticketInfo`,'$.issuedAt'))) VIRTUAL NOT NULL,
`expiresAt` timestamp GENERATED ALWAYS AS (json_unquote(json_extract(`ticketInfo`,'$.expiresAt'))) VIRTUAL NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `VehicleTickets_externalId_unq_idx` (`externalId`,`organizationId`),
KEY `VehicleTickets_vehiclePlate_idx` (`vehiclePlate`),
KEY `VehicleTickets_organizationId_idx` (`organizationId`),
KEY `VehicleTickets_issuedAt_idx` (`createdAt`),
KEY `VehicleTickets_expiresAt_idx` (`expiresAt`),
CONSTRAINT `VehicleTickets_Organizations_fk`
FOREIGN KEY (`organizationId`) REFERENCES `Organizations` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE `Organizations` (
`id` varchar(50) NOT NULL,
`name` varchar(100) NOT NULL,
`taxPayerId` varchar(50) DEFAULT NULL,
`businessName` varchar(100) DEFAULT NULL,
`status` varchar(15) NOT NULL DEFAULT 'TESTING',
`createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updatedAt` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`activatedAt` timestamp NULL DEFAULT NULL,
`assetConfiguration` json DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
When I run:
select * from VehicleTickets where organizationId not in (
select id from Organizations
);
I get an empty result set.
However, if I run a query like this:
insert into `VehicleTickets` (
`id`,
`createdAt`,
`organizationId`,
`ticketInfo`,
`vehiclePlate`
)
values (
'... application generated id',
'... current date ',
'cjlchoksi01r8nfks3f51kht8', -- DOES EXIST on Organizations
'{ ... some JSON payload }',
'... vehicle plate'
)
This produces the following error:
Cannot add or update a child row: a foreign key constraint fails
(VehicleTickets, CONSTRAINT VehicleTickets_Organizations_fk
FOREIGN KEY (organizationId) REFERENCES Organizations (id))
Additionally, it gives me:
"errno": 1452,
"sqlState": "23000",
I've read through several threads regarding this issue, but couldn't find a similar case.

MySQL Workbench wont make constraint when parent table has Generated Virtual columns

SETUP
MySQL Workbench (ver 6.3.9)
MySQL 5.7.21
My setup is simple.. I have 2 tables:
CREATE TABLE `UserDevices` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`UserID` int(11) DEFAULT NULL,
`UUID` binary(16) DEFAULT NULL,
`DeviceName` varchar(45) DEFAULT NULL,
`DeviceType` tinyint(3) NOT NULL DEFAULT '1',
`CreatedDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`TimeStamp` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
CREATE TABLE `UserInfo` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`UUID` binary(16) DEFAULT NULL,
`UUIDText` varchar(40) GENERATED ALWAYS AS (insert(insert(insert(insert(hex(`UUID`),9,0,'-'),14,0,'-'),19,0,'-'),24,0,'-')) VIRTUAL,
`FirstName` varchar(45) DEFAULT NULL,
`LastName` varchar(45) DEFAULT NULL,
`FullName` varchar(90) GENERATED ALWAYS AS (concat(`FirstName`,' ',`LastName`)) VIRTUAL,
`Email` varchar(120) DEFAULT NULL,
`Status` tinyint(3) DEFAULT '0',
`AccountType` tinyint(3) DEFAULT '1',
`CreatedDate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`TimeStamp` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
PROBLEM
When working inside Workbench I'm simply trying to Make a Foreign key constraint in table "UserDevices" on Column "UserID" Pointed at Table "UserInfo" Column "ID". When selecting "UserInfo" as the Referenced Table. I can not put a check next to UserID.. Also no columns show up in the drop down list under Referenced Column..
QUESTION
I understand there are a number of reasons this scenario would happen. But I'm not seeing Any data type mismatch or such that would explain this. What is making it so I can't select UserID.ID?
P.S. Setting up another table named "DeviceMeasurements" with a Column "DeviceID" I'm completely successful at setting up the constraint exactly as expected.
UPDATE
On a hunch since this is my first time playing around with Generated Virtual Columns. I went into the table and removed columns "UUIDText" and "FullName". NOW I can build my constraints as desired. But my question stands. Why can't I build constraint with the tables built as above!?
UPDATE 2
This has been confirmed as a bug in WorkBench. Manually adding the constraint via SQL code is a valid work around currently. Please see accepted answer.
Can confirm, this is a bug in WB. Have raised it with MySQL dev team.
Bug link

Error when importing schema.sql

I'm new to sql, currently I am using phpMyAdmin via XAMP, I think that uses mysql so correct me if I'm wrong by saying that. Anywhos, I'm trying to import a schema.sql data file into my database I created called "test" but I got an error upon importing it:
It says
Import has been successfully finished, 1 queries executed.
(schema.sql)
But then it also gives me an error message:
CREATE TABLE `population` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`location` varchar(150) NOT NULL,
`slug` varchar(150) NOT NULL,
`population` int(10) unsigned NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8
MySQL said: Documentation
1075 - Incorrect table definition; there can be only one auto column and it must be defined as a key
and :
Notice in .\import.php#704 Undefined variable: import_text Backtrace
I'm not sure what the issue is. The database I created is completely and has nothing in it.
Column id is the auto-column in question; auto-columns need to be defined as a key, for example as a unique key or a primary key. In your case, a primary key is a good idea because - well, it's your id-column.
CREATE TABLE `population` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`location` varchar(150) NOT NULL,
`slug` varchar(150) NOT NULL,
`population` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

MySQL ERROR 1064 in line, but don't know what is wrong?

I've got the following line I want to execute in MySQL:
CREATE TABLE 'virtual_domains' (
'id' int(11) NOT NULL auto_increment,
'name' varchar(50) NOT NULL,
PRIMARY KEY ('id'))
ENGINE=InnoDB DEFAULT CHARSET=utf8;
However, it gave me this error:
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 ''virtual_domains' ('id' int(11) NOT NULL
auto_increment, 'name' varchar(50) NOT ' at line 1
What am I missing here??
Thanks for the help!
Rob
remove the single quotes around the table and column names. use backticks instead.
CREATE TABLE `virtual_domains` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(50) NOT NULL,
PRIMARY KEY (`id`))
ENGINE=InnoDB DEFAULT CHARSET=utf8;
In addition to use of backticks (`symbol`), since none of the identifiers you have used require escaping, you can simply remove the escaping altogether:
CREATE TABLE virtual_domains (
id int(11) NOT NULL auto_increment,
name varchar(50) NOT NULL,
PRIMARY KEY (id))
ENGINE=InnoDB DEFAULT CHARSET=utf8;
Alternatively when you do need to escape symbols, instead of using backticks, consider using ANSI compliant quotes ("symbol"). You will need to set SQL_MODE=ANSI_QUOTES:
SET SQL_MODE=ANSI_QUOTES;
CREATE TABLE "virtual_domains" (
"id" int(11) NOT NULL auto_increment,
"name" varchar(50) NOT NULL,
PRIMARY KEY ("id"))
ENGINE=InnoDB DEFAULT CHARSET=utf8;
The benefit of this is improved portability between the various RDBMS.
SqlFiddle here

mySQL trigger? causing Error Code: 1048 Column cannot be null

I have seen similar questions asked but never seen an answer that works for me. I have the following table and trigger definitions...
DROP TRIGGER IF EXISTS c_consumption.newRateHistory;
DROP TABLE IF EXISTS c_consumption.myrate;
DROP TABLE IF EXISTS c_consumption.myratehistory;
USE c_consumption;
CREATE TABLE `myrate` (
`consumerId` varchar(255) DEFAULT NULL,
`durationType` varchar(50) NOT NULL DEFAULT 'DAY',
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`itemId` varchar(50) NOT NULL,
`quantity` double NOT NULL DEFAULT 1.0,
`quantityType` varchar(100) NOT NULL DEFAULT 'GALLON',
`timePeriod` double NOT NULL DEFAULT 1.0,
PRIMARY KEY (`id`),
UNIQUE INDEX `UNIQUE_RATE`
(`itemId` ASC, `consumerId` ASC)
) ENGINE=InnoDB AUTO_INCREMENT=314 DEFAULT CHARSET=utf8;
CREATE TABLE `myratehistory` (
`consumerId` varchar(255) DEFAULT NULL,
`durationType` varchar(50) DEFAULT NULL,
`itemId` varchar(50) NOT NULL,
`quantity` double DEFAULT NULL,
`quantityType` varchar(100) DEFAULT NULL,
`status` varchar(20) NOT NULL DEFAULT 'CREATED',
`timePeriod` double DEFAULT NULL,
`timestamp` DATETIME NULL,
PRIMARY KEY (`itemId`, `consumerId`, `timestamp`)
) ENGINE=InnoDB AUTO_INCREMENT=314 DEFAULT CHARSET=utf8;
CREATE TRIGGER `newRateToHistory`
AFTER INSERT
ON myrate
FOR EACH ROW
INSERT INTO myratehistory
(
consumerId,
durationType,
itemId,
quantity,
quantityType,
status,
timePeriod,
timestamp
)
VALUES(
new.consumerId,
new.durationType,
new.itemId,
new.quantity,
new.quantityType,
'CREATED',
new.timePeriod,
now());
Note that consumerId CAN be null.
Next I run this SQL statement:
INSERT INTO c_consumption.myrate (
consumerId,
durationType,
itemId,
quantity,
quantityType,
timePeriod)
VALUES(
null,
'DAY',
'MyItem',
1.0,
'GALLON',
1.0);
I get the following message:
Error Code: 1048 Column 'consumerId' cannot be null
Obviously I am doing something wrong but I do not know what it is. Any help would be greatly appreciated.
Thanks!
ConsumerId is part of the primary key. No part of the primary key can be null.
Just a guess, why mysql allows a null-able column as part of the primary key I don't know
CREATE TABLE `myratehistory` (
[...]
PRIMARY KEY (`itemId`, `consumerId`, `timestamp`)
Your MySQL server is running in "strict" mode, which throws an error in case like yours are otherwise handled "gracefully" without strict mode.
As of MySQL 5.7.5, the default SQL mode includes STRICT_TRANS_TABLES, which is exactly the cause of your headache.
To change your server's mode, edit your my.cnf (or my.ini if you're running Windows) and set the mode to:
sql-mode=""
Then you must restart your mysql server like this:
service mysql reload
Or directly throw init.d process:
/etc/init.d/mysql reload
Hope it will help you.