Error 1005: Can't create table - mysql

im trying to drop a table and before i had this problem QUESTION
and was solved succesfully but now i tried to drop the table and i got this error :
ERROR: Error 1005: Can't create table 'radiotaxi_final.#sql-108_28' (errno: 150)
the statement :
ALTER TABLE `RadioTaxi_Final`.`DireccionConductor` CHANGE COLUMN `Conductor_cedula` `Conductor_cedula` INT(11) NOT NULL ,
ADD CONSTRAINT `fk_DireccionConductor_Conductor1`
FOREIGN KEY (`Conductor_cedula` )
REFERENCES `RadioTaxi_Final`.`Conductor` (`cedula` )
ON DELETE NO ACTION
ON UPDATE NO ACTION
the results :
SQL script execution finished: statements: 11 succeeded, 1 failed
the table :
CREATE TABLE `conductor` (  `cedula` int(10) unsigned NOT NULL,  `apellidos` varchar(30) COLLATE utf8_spanish2_ci NOT NULL,  `nombres` varchar(30) COLLATE utf8_spanish2_ci NOT NULL,  `fechaNacimiento` date NOT NULL,  PRIMARY KEY (`cedula`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci

When creating a FOREIGN KEY, the data types of the referenced and referencing columns must be exactly the same. In your referenced table, conductor.cedula is of type INT(10) UNSIGNED. You have attempted to create the FK on DireccionConductor.Conductor_cedula as INT(11), implicitly SIGNED. modify your statement as follows to make the type match:
ALTER TABLE `RadioTaxi_Final`.`DireccionConductor`
/* INT(10) UNSIGNED type matches the referenced table */
CHANGE COLUMN `Conductor_cedula` `Conductor_cedula` INT(10) UNSIGNED NOT NULL ,
ADD CONSTRAINT `fk_DireccionConductor_Conductor1`
FOREIGN KEY (`Conductor_cedula` )
REFERENCES `RadioTaxi_Final`.`Conductor` (`cedula` )
ON DELETE NO ACTION
ON UPDATE NO ACTION

Related

The duplicate key value is (<NULL>, <NULL>)

So I'm trying to migrate a table from MySQL to MSSQL (sql server migration assistant MySQL), but I get this error:
Migrating data...
Analyzing metadata...
Preparing table testreportingdebug.testcase...
Preparing data migration package...
Starting data migration Engine
Starting data migration...
The data migration engine is migrating table '`testreportingdebug`.`testcase`': > [SwMetrics].[testreportingdebug].[testcase], 8855 rows total
Violation of UNIQUE KEY constraint 'testcase$Unique'. Cannot insert duplicate key in object 'testreportingdebug.testcase'. The duplicate key value is (<NULL>, <NULL>).
Errors: Violation of UNIQUE KEY constraint 'testcase$Unique'. Cannot insert duplicate key in object 'testreportingdebug.testcase'. The duplicate key value is (<NULL>, <NULL>).
Completing migration of table `testreportingdebug`.`testcase`...
Migration complete for table '`testreportingdebug`.`testcase`': > [SwMetrics].[testreportingdebug].[testcase], 0 rows migrated (Elapsed Time = 00:00:00:01:352).
Data migration operation has finished.
0 table(s) successfully migrated.
0 table(s) partially migrated.
1 table(s) failed to migrate.
I've just copied three rows from my table, and this is what they look like:
'1', 'Pump# TimeToService', NULL, NULL, 'A general test case comment ...', '0'
'2', 'Config.SlaveMinimumReplyDelay', NULL, NULL, NULL, '0'
'3', 'Config.RESERVED', NULL, NULL, NULL, '0'
If you are wondering how the colons in the MySQL table is setup, here you go:
Is is because right, left and comment can be null?
DDL of table
CREATE TABLE `testcase` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`TestCaseName` varchar(150) DEFAULT NULL,
`Left` int(11) DEFAULT NULL,
`Right` int(11) DEFAULT NULL,
`Comment` text,
`Hidden` tinyint(4) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
UNIQUE KEY `Unique` (`Left`,`Right`)
) ENGINE=InnoDB AUTO_INCREMENT=10580 DEFAULT CHARSET=utf8
Had to remove the Unique part, since their are only NULL.
ALTER TABLE `testreportingdebug`.`testcase`
DROP INDEX `Unique`;
If you want the strict equivalent in SQL Server of your MySQL table you must create it like this :
CREATE TABLE testcase (
id int NOT NULL IDENTITY PRIMARY KEY,
TestCaseName varchar(150),
[Left] int,
[Right] int,
Comment VARCHAR(max),
[Hidden] tinyint DEFAULT 0,
);
CREATE UNIQUE INDEX X_testcase_right_left
ON testcase ([Left], [Right])
WHERE [Left] IS NOT NULL
AND [Right] IS NOT NULL;
By the way, column names "Right", "left", "hidden" are SQL / MS SQL Server reserved words and should not be used at anytime for SQL identifiers (table name, colum name, proc name...)
The complete list can be obtain here

Weird MySQL Model synchronization error

Why do I get this weird error when trying to synchronise my model with the mysql database (v5.7.19, workbench v6.3.9)? As you can see from the screenshot, table1_createdOn doesn't even have a default valid, and if i run the generated command with sql query it works:
CREATE SCHEMA IF NOT EXISTS `mydb` DEFAULT CHARACTER SET utf8 ;
CREATE TABLE IF NOT EXISTS `mydb`.`table1` (
`createdOn` TIMESTAMP NOT NULL,
PRIMARY KEY (`createdOn`))
CREATE TABLE IF NOT EXISTS `mydb`.`table2` (
`createdAt` TIMESTAMP NOT NULL,
`table1_createdOn` TIMESTAMP NOT NULL,
PRIMARY KEY (`table1_createdOn`),
CONSTRAINT `fk_round_table1`
FOREIGN KEY (`table1_createdOn`)
REFERENCES `mydb`.`table1` (`createdOn`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)

SQL commands not compliable by H2

The following SQL commands are actually for MySQL. I am not a SQL expert and do not know much about H2. My Spring app throws an exception because the user_roles table can not be created. It has a problem with the fk_username_idx:
DROP TABLE IF EXISTS users;
DROP TABLE IF EXISTS user_roles;
CREATE  TABLE users (
  userid VARCHAR(5) NOT NULL,
  username VARCHAR(45) NOT NULL ,
  password VARCHAR(60) NOT NULL ,
  enabled TINYINT NOT NULL DEFAULT 1 ,
  PRIMARY KEY (userid));
   
CREATE TABLE user_roles (
  user_role_id int(11) NOT NULL AUTO_INCREMENT,
  userid varchar(5) NOT NULL,
  role varchar(45) NOT NULL,
  PRIMARY KEY (user_role_id),
  UNIQUE KEY uni_username_role (role,userid),
  KEY fk_username_idx (userid),
  CONSTRAINT fk_username FOREIGN KEY (userid) REFERENCES users (userid));
ERROR LOG:
Caused by: org.h2.jdbc.JdbcSQLException: Unbekannter Datentyp: "FK_USERNAME_IDX"
Unknown data type: "FK_USERNAME_IDX"; SQL statement:
   CREATE TABLE user_roles (   user_role_id int(11) NOT NULL AUTO_INCREMENT,   userid varchar(5) NOT NULL,   role varchar(45) NOT NULL,   PRIMARY KEY (user_role_id),   UNIQUE KEY uni_username_role (role,userid),   KEY fk_username_idx (userid),   CONSTRAINT fk_username FOREIGN KEY (userid) REFERENCES users (userid)) [50004-191]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
at org.h2.message.DbException.get(DbException.java:179)
at org.h2.message.DbException.get(DbException.java:155)
at org.h2.command.Parser.parseColumnWithType(Parser.java:4059)
at org.h2.command.Parser.parseColumnForTable(Parser.java:3922)
at org.h2.command.Parser.parseCreateTable(Parser.java:5864)
at org.h2.command.Parser.parseCreate(Parser.java:4217)
at org.h2.command.Parser.parsePrepared(Parser.java:360)
at org.h2.command.Parser.parse(Parser.java:315)
at org.h2.command.Parser.parse(Parser.java:287)
at org.h2.command.Parser.prepareCommand(Parser.java:252)
at org.h2.engine.Session.prepareLocal(Session.java:560)
at org.h2.engine.Session.prepareCommand(Session.java:501)
at org.h2.jdbc.JdbcConnection.prepareCommand(JdbcConnection.java:1188)
at org.h2.jdbc.JdbcStatement.executeInternal(JdbcStatement.java:170)
at org.h2.jdbc.JdbcStatement.execute(JdbcStatement.java:158)
at org.springframework.jdbc.datasource.init.ScriptUtils.executeSqlScript(ScriptUtils.java:472)
... 47 more
are you sure your H2 runs in MySQL compatiblity mode? Check this first. By looking at the connect string. For example like this:
final SimpleDriverDataSource ds = new SimpleDriverDataSource();
ds.setDriverClass(Driver.class);
ds.setUrl("jdbc:h2:mem:test;MODE=mysql;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE");
ds.setUsername("sa");
ds.setPassword("");
FOREIGN KEY fk_username_idx (userid), is not suppported by H2. Remove FOREIGN here.
Then it will work

Inserting Foreign Key using MySQL Workbench code throwing Syntax Error

I have created several tables with MySQL Workbench and I'm having a problem with Foreign Keys. If I export code below I get an error however if I do not export with foreign keys I do not get an error could you have a look at the code for me.
SQL Code:
DROP TABLE IF EXISTS `mydb`.`users` ;
CREATE TABLE IF NOT EXISTS `mydb`.`users` (
`uuserid` INT NOT NULL AUTO_INCREMENT ,
`ufname` VARCHAR(25) NULL ,
`ulname` VARCHAR(25) NULL ,
`uuname` VARCHAR(45) NULL ,
`upass` CHAR(64) NOT NULL ,
`uemail` VARCHAR(254) NOT NULL ,
`urole` INT NULL DEFAULT 0 ,
PRIMARY KEY (`uuserid`) )
ENGINE = InnoDB;
DROP TABLE IF EXISTS `mydb`.`photos` ;
CREATE TABLE IF NOT EXISTS `mydb`.`photos` (
`pphotoid` INT NOT NULL ,
`pname` VARCHAR(4) NULL ,
`plat` FLOAT(10,6) NULL ,
`plng` FLOAT(10,6) NULL ,
`pflag` DECIMAL(10,0) NULL DEFAULT 0 ,
`pext` VARCHAR(4) NULL ,
`plike` DECIMAL(10,0) NULL DEFAULT 0 ,
PRIMARY KEY (`pphotoid`) ,
CONSTRAINT `uuserid`
FOREIGN KEY ()
REFERENCES `mydb`.`users` ()
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
Error:
#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 ') REFERENCES `mydb`.`users` () ON DELETE NO ACTION ON UPDAT' at line 21
My Database has many more tables but this code also breaks. I have tried to insert this using phpmyadmin.
Here you need to specify the column name
FOREIGN KEY (present_table_column_name)
REFERENCES mydb.users (foriegn_key_column_name)
Try running this script. I build this using your script and ran it in SQLFiddle so I know it works. In order to add a foreign key you have to have a field that will be appropriate. In this example I added a uuserid column in the photos table. This column has a foreign key constraint to the uuserid column in the users table.
DROP TABLE IF EXISTS `mydb`.`users` ;
CREATE TABLE IF NOT EXISTS `mydb`.`users` (
`uuserid` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
`ufname` VARCHAR(25) NULL ,
`ulname` VARCHAR(25) NULL ,
`uuname` VARCHAR(45) NULL ,
`upass` CHAR(64) NOT NULL ,
`uemail` VARCHAR(254) NOT NULL ,
`urole` INT NULL DEFAULT 0
) ENGINE = InnoDB;
DROP TABLE IF EXISTS `mydb`.`photos` ;
CREATE TABLE IF NOT EXISTS `mydb`.`photos` (
`pphotoid` INT NOT NULL PRIMARY KEY,
`pname` VARCHAR(4) NULL ,
`plat` FLOAT(10,6) NULL ,
`plng` FLOAT(10,6) NULL ,
`pflag` DECIMAL(10,0) NULL DEFAULT 0 ,
`pext` VARCHAR(4) NULL ,
`plike` DECIMAL(10,0) NULL DEFAULT 0,
`uuserid`INT NOT NULL
) ENGINE = InnoDB;
Alter Table `photos` add constraint foreign key(`uuserid`) references `users`(`uuserid`);
In this example above, I moved the statement that sets the primary keys to the columns themselves rather than creating a statement at the end of the SQL.
I thought it would be a little clearer to show you how to add a foreign key constraint outside of the table creation so you can see what caused the syntax error. You had no column names in your foreign key references. Once added the above code will run perfectly.
You have a syntax error exactly where the error message tells you you have one.
The problem is you don't have you have any fields referenced in your constraint. The form of the CONSTRAINT clause should be like this:
CONSTRAINT `fkuuserid`
FOREIGN KEY `fkuuserid` (some_field_in_this_table)
REFERENCES `mydb`.`users` (uuserid)
ON DELETE NO ACTION
ON UPDATE NO ACTION
I honestly don't even see where you have a logical foreign key on the photos table, as there is no uuserid field present in this table.

MySQL workbench - self referring table and custom script

I use MySQL 5.3.28 to create my database. One of the tables is referring itself, which is a big pain. Here is the originally created code:
CREATE TABLE IF NOT EXISTS `dhbpsychiatry`.`activity` (
`ActivityId` INT(11) NOT NULL AUTO_INCREMENT ,
`NeedsRepeating` BINARY(1) NULL DEFAULT NULL ,
`Prerequisition` INT(11) NOT NULL DEFAULT 0 ,
`ActivityName` VARCHAR(45) NOT NULL ,
`ActivityDescription` VARCHAR(45) NULL ,
PRIMARY KEY (`ActivityId`) ,
INDEX `Prerequisition` (`ActivityId` ASC) ,
CONSTRAINT `Prerequisition`
FOREIGN KEY (`ActivityId` )
REFERENCES `dhbpsychiatry`.`activity` (`ActivityId` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
Problem is of course with creating first row.
INSERT INTO `dhbpsychiatry`.`activity` (`ActivityId`, `Prerequisition`,
`ActivityName`) VALUES (1, 1, 'No prerequisition');
returns
ERROR 1452: Cannot add or update a child row: a foreign key constraint fails
Same if I try even simpler
INSERT INTO `dhbpsychiatry`.`activity` (`ActivityName`)
VALUES ('No prerequisition');
I think I've tried all possibilities, making the FK nullable, not nullable, with or without default value...
After digging a bit I've found something that works:
SET FOREIGN_KEY_CHECKS = 0;
Insert into activity (ActivityID, ActivityName) VALUES (0,'No prerequisition');
SET FOREIGN_KEY_CHECKS = 1;
So I created a new SQL script in workbench with those lines.
So I have two questions here:
How I can add the first row without the script?
or if its impossible
2 How can I automatically add this script to be executed whenever I froward engineer the database?
Your indexes and Foreign key definitions are confused. Main issue is that column ActivityId is referencing itself.
Try this:
CREATE TABLE IF NOT EXISTS `dhbpsychiatry`.`activity` (
`ActivityId` INT(11) NOT NULL AUTO_INCREMENT ,
`NeedsRepeating` BINARY(1) NULL DEFAULT NULL ,
`Prerequisition` INT(11) NOT NULL DEFAULT 0 ,
`ActivityName` VARCHAR(45) NOT NULL ,
`ActivityDescription` VARCHAR(45) NULL ,
PRIMARY KEY (`ActivityId`) ,
INDEX `Prerequisition_idx` (`Prerequisition`) , --- changed the index name
--- and the indexed column
CONSTRAINT `Prerequisition_fk` --- changed the constraint name
FOREIGN KEY (`Prerequisition` ) --- main issue !! changed
--- the referencing column
REFERENCES `dhbpsychiatry`.`activity` (`ActivityId`)
ON DELETE NO ACTION
ON UPDATE NO ACTION
)