MySQL 5.7 Windows, table key issue? - mysql

What is wrong with this MySQL table script code?:
CREATE TABLE `securities_master`.`symbol` (
`id` INT NOT NULL,
`exchange_id` INT NULL,
`ticker` VARCHAR(32) NOT NULL,
`instrument` VARCHAR(64) NOT NULL,
`name` VARCHAR(255) NULL,
`sector` VARCHAR(255) NULL,
`currency` VARCHAR(32) NULL,
`created_date` DATETIME NOT NULL,
`last_updated_date` DATETIME NOT NULL,
PRIMARY KEY (`id`), FOREIGN KEY 'index_exchange_id' ('exchange_id'))
ENGINE = InnoDB AUTO_INCREMENT = 1
DEFAULT CHARACTER SET = utf8;
I think it is the "FOREIGN KEY" but I am not sure

Single quotes denote string literals in SQL. Object names (such as the constraint name and the columns it refers to) should be denoted with backticks, or nothing at all:
CREATE TABLE `securities_master`.`symbol` (
`id` INT NOT NULL,
`exchange_id` INT NULL,
`ticker` VARCHAR(32) NOT NULL,
`instrument` VARCHAR(64) NOT NULL,
`name` VARCHAR(255) NULL,
`sector` VARCHAR(255) NULL,
`currency` VARCHAR(32) NULL,
`created_date` DATETIME NOT NULL,
`last_updated_date` DATETIME NOT NULL,
PRIMARY KEY (`id`),
FOREIGN KEY `index_exchange_id` (`exchange_id`)
-- Here ----^-----------------^--^-----------^
)
ENGINE = InnoDB AUTO_INCREMENT = 1
DEFAULT CHARACTER SET = utf8;

Related

MySQL foreign key not found even if it exists

I have 2 tables 'open_invoices' and 'paid_invoices' with the below structures:
CREATE TABLE `open_invoices` (
`id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`unique_identifier` varchar(255) NOT NULL,
`insert_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`cust_nbr` int(11) NOT NULL,
`location` varchar(10) NOT NULL,
`company` varchar(10) NOT NULL,
`invoice_nbr` int(11) NOT NULL,
`future_letter` varchar(1) NOT NULL,
`invoice_total` decimal(8,2) NOT NULL,
`invoice_payments` decimal(8,2) NOT NULL,
`record_type` int(11) NOT NULL,
`terms_desc` varchar(255) NOT NULL,
`due_date` varchar(8) NOT NULL,
`discount_date` varchar(8) NOT NULL,
`orig_disc_avail` decimal(8,2) NOT NULL,
`cust_po` varchar(10) NOT NULL,
`invoice_date` varchar(8) NOT NULL,
`status` int(11) NOT NULL,
`check_no` varchar(10) NOT NULL,
`last_pay_date` varchar(8) NOT NULL,
`as_of_date` varchar(8) NOT NULL,
`as_of_time` varchar(11) NOT NULL,
`remaining` varchar(1) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `unique_identifier` (`unique_identifier`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `paid_invoices` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`date_change` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`invoice_date` varchar(8) NOT NULL,
`unique_identifier` varchar(255) NOT NULL,
`amount_paid` decimal(8,2) NOT NULL,
`amount_left` decimal(8,2) NOT NULL,
`payment_type` varchar(2) NOT NULL,
`last4` varchar(255) NOT NULL,
`transac_id` varchar(255) NOT NULL,
`customer_id` varchar(255) NOT NULL,
`payment_P_F` varchar(1) NOT NULL,
PRIMARY KEY (`id`),
FOREIGN KEY (unique_identifier)
REFERENCES open_invoices (unique_identifier)
ON DELETE CASCADE
ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
I'm trying to insert a row in 'paid_invoices' like below:
INSERT INTO `paid_invoices` (`invoice_date`, `unique_identifier`, `amount_paid`, `amount_left`, `payment_type`, `last4`, `transac_id`, `customer_id`, `payment_P_F`) VALUES ('07/19/18', '126_89948_2576', 0, '37.45', '', '', '', '13776', 'P')
I get the below error:
Error Number: 1452
Cannot add or update a child row: a foreign key constraint fails (`accounts_receivables`.`paid_invoices`, CONSTRAINT `paid_invoices_ibfk_1` FOREIGN KEY (`unique_identifier`) REFERENCES `open_invoices` (`unique_identifier`))
INSERT INTO `paid_invoices` (`invoice_date`, `unique_identifier`, `amount_paid`, `amount_left`, `payment_type`, `last4`, `transac_id`, `customer_id`, `payment_P_F`) VALUES ('07/19/18', '126_89948_2576', 0, '37.45', '', '', '', '13776', 'P')
If I search on google, it says that the foreign key 126_89948_2576 was not found in the table 'open_invoices'.
When I do SELECT * FROM open_invoices WHERE id = 2576 I see the row with the foreign key 126_89948_2576 as shown in the picture below :
[![query 1][1]][1]
but when I do this query SELECT * FROM open_invoices WHERE unique_identifier = '126_89948_2576' I get no result see capture below:
[![query 2][2]][2]
I'm sure there is no extra blank space in the value saved for foreign key 126_89948_2576.
What is going on please? Is there a bug in the version of MySQL I'm using?
Server: Localhost via UNIX socket
Server type: MySQL
Server version: 5.6.40 - MySQL Community Server (GPL)
Protocol version: 10
Thanks.
[1]: https://i.stack.imgur.com/L2QDX.png
[2]: https://i.stack.imgur.com/T9Fz5.png
It seems you are using wrong divider symbols, "_" instead of "-" in your query. Try unique_identifier = '126-89948-2576'
Because the underscore _ is a wildcard like the percent %, except that it only looks for one character.
SQL pattern matching enables you to use "_" to match any single character and "%" to match an arbitrary number of characters (including zero characters).
you can use
SELECT * FROM open_invoices WHERE unique_identifier like '%126\_89948\_2576%'

Is this mysql correctly translated to sql server?

I have this, for mysql
CREATE TABLE IF NOT EXISTS `users` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`email` varchar(249) COLLATE utf8mb4_unicode_ci NOT NULL,
`password` varchar(255) CHARACTER SET latin1 COLLATE latin1_general_cs NOT NULL,
`username` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`verified` tinyint(1) unsigned NOT NULL DEFAULT '0',
`registered` int(10) unsigned NOT NULL,
`last_login` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `email` (`email`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
I'm attempting to convert to sql server:
CREATE TABLE users(
id int PRIMARY KEY IDENTITY NOT NULL,
email varchar(255) UNIQUE,
password varchar(255) NOT NULL ,
username varchar(100) DEFAULT NULL,
verified tinyint NOT NULL DEFAULT '0',
registered int NOT NULL,
last_login int DEFAULT NULL,
);
That worked, but I had to omit some things, mostly the Collate and character set. Can you tell me if I missed anything too important and how to translate those things from mysql to sql server?
Some notes:
PRIMARY KEY means NOT NULL.
Constants should be in the same type as their variable.
For generalized character sets, use NVARCHAR().
DEFAULT NULL is redundant (you can keep it if you like).
Hence:
CREATE TABLE users (
id int PRIMARY KEY IDENTITY,
email nvarchar(255) UNIQUE,
password nvarchar(255) NOT NULL ,
username nvarchar(100),
verified tinyint NOT NULL DEFAULT 0,
registered int NOT NULL,
last_login int
);

Mysql error 1215 - Cannot add foreign key constraint

Created these two tables successfully
First table
CREATE TABLE IF NOT EXISTS `lawncare_user` (
`ID` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`FirstName` varchar(255) NOT NULL,
`LastName` varchar(255) NOT NULL,
`Email` varchar(255) NOT NULL,
`UserType` varchar(30) NOT NULL,
`UserName` varchar(255) NOT NULL,
`Password` varchar(255) NOT NULL,
`AddedBy` int(11) NOT NULL,
`AddedOn` date NOT NULL,
`ModifiedOn` date DEFAULT NULL,
`Status` BOOLEAN NOT NULL DEFAULT '0',
`QuestionID` int(11) DEFAULT NULL,
`QuestionAnswer` text DEFAULT NULL,
`Params` text NOT NULL,
`Address` text NOT NULL,
`Country` varchar(300) NOT NULL,
`State` varchar(300) NOT NULL,
`City` varchar(300) NOT NULL,
`ContactNo` double DEFAULT NULL,
`Activation` BOOLEAN NOT NULL DEFAULT '0',
`ActivatedOn` date DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Second table
CREATE TABLE IF NOT EXISTS `lawncare_customer` (
`ID` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`FirstName` varchar(255) NOT NULL,
`LastName` varchar(255) NOT NULL,
`Email` varchar(255) NOT NULL,
`Password` varchar(255) NOT NULL,
`ContactNo` varchar(20) NOT NULL,
`Address` varchar(255) NOT NULL,
`Params` text NOT NULL,
`Province` varchar(255) NOT NULL,
`ZipCode` varchar(255) NOT NULL,
`Status` Boolean NOT NULL DEFAULT '0',
`AddedBy` int(11) NOT NULL,
`AddedOn` date NOT NULL,
`ModifiedOn` date DEFAULT NULL
) ENGINE =InnoDB DEFAULT CHARSET=latin1;
But while creating third table as
CREATE TABLE IF NOT EXISTS `lawncare_message` (
`ID` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`Reason` int(5) NOT NULL,
`Subject` text NOT NULL,
`Description` text NOT NULL,
`Customer` int(11) NOT NULL,
`CustomerUser` varchar(255) NOT NULL,
`CustomerEmail` varchar(255) NOT NULL,
`SendTo` int(11) NOT NULL,
`SendToUser` varchar(255) NOT NULL,
`SendToEmail` varchar(255) NOT NULL,
`Status` int(5) NOT NULL DEFAULT '0',
`AddedBy` int(11) NOT NULL,
`AddedOn` date NOT NULL
FOREIGN KEY (SendTo, SendToUser, SendToEmail)
REFERENCES lawncare_user(ID, UserName, Email)
ON UPDATE CASCADE ,
FOREIGN KEY (Customer, CustomerUser, CustomerEmail)
REFERENCES lawncare_customer(ID, FirstName,Email)
ON UPDATE CASCADE
) ENGINE =InnoDB DEFAULT CHARSET=latin1
I get #1215 - Cannot add foreign key constraint , error in mysql tried adding foreign keys after creating table but it still gives the same error. I don't know what I'm doing wrong here.
First of all Check whether you have applied indexes on the keys.
As per your code their is no point in referencing id,UserName and Email.
Only id is enough for referencing.
Check the following code
CREATE TABLE IF NOT EXISTS `lawncare_message` (
`ID` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`Reason` int(5) NOT NULL,
`Subject` text NOT NULL,
`Description` text NOT NULL,
`Customer` int(11) NOT NULL,
`CustomerUser` varchar(255) NOT NULL,
`CustomerEmail` varchar(255) NOT NULL,
`SendTo` int(11) NOT NULL,
`SendToUser` varchar(255) NOT NULL,
`SendToEmail` varchar(255) NOT NULL,
`Status` int(5) NOT NULL DEFAULT '0',
`AddedBy` int(11) NOT NULL,
`AddedOn` date NOT NULL,
FOREIGN KEY (SendTo)
REFERENCES lawncare_user(ID)
ON UPDATE CASCADE ,
FOREIGN KEY (Customer)
REFERENCES lawncare_customer(ID)
ON UPDATE CASCADE
) ENGINE =InnoDB DEFAULT CHARSET=latin1

Not able to create a Foreign Constraint in Mysql

Here is the script I am trying to run
CREATE TABLE IF NOT EXISTS `store` (
`store_id` INT NOT NULL AUTO_INCREMENT,
`store_name` VARCHAR(1024) NOT NULL,
`store_user` INT NOT NULL,
`store_address` INT NOT NULL,
`store_type` INT NOT NULL,
`created_date` DATETIME NOT NULL,
`updated_date` DATETIME NOT NULL,
PRIMARY KEY (`store_id`)
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS `store_address` (
`address_id` INT NOT NULL AUTO_INCREMENT,
`address_line_1` VARCHAR(1024) NOT NULL,
`address_line_2` VARCHAR(1024) NOT NULL,
`address_line_3` VARCHAR(1024) NULL,
`city` VARCHAR(45) NOT NULL,
`locality` VARCHAR(100) NOT NULL,
`pincode` CHAR(6) NOT NULL,
`latitude` DECIMAL(8,6) NULL,
`longitude` DECIMAL(9,6) NULL,
`state` VARCHAR(45) NOT NULL,
`created_date` DATETIME NOT NULL,
`updated_date` DATETIME NOT NULL,
PRIMARY KEY (`address_id`),
CONSTRAINT `FK_STR_STR_ADR`
FOREIGN KEY (`address_id`)
REFERENCES `store` (`store_address`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
I get this error - Error Code: 1215. Cannot add foreign key constraint
No clue what is wrong with the DDL
Two issues:
1. use unsigned int for the primary keys (Edit: this is a good idea but was not the problem)
2. the store.store address must be a key in the store table in order to use it in a foreign key constraint in the store_address table
CREATE TABLE IF NOT EXISTS `store` (
`store_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`store_name` VARCHAR(1024) NOT NULL,
`store_user` INT NOT NULL,
`store_address` int(10) unsigned NOT NULL DEFAULT 0,
`store_type` INT NOT NULL,
`created_date` DATETIME NOT NULL,
`updated_date` DATETIME NOT NULL,
PRIMARY KEY (`store_id`),
KEY (`store_address`)
) ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS `store_address` (
`address_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`address_line_1` VARCHAR(1024) NOT NULL,
`address_line_2` VARCHAR(1024) NOT NULL,
`address_line_3` VARCHAR(1024) NULL,
`city` VARCHAR(45) NOT NULL,
`locality` VARCHAR(100) NOT NULL,
`pincode` CHAR(6) NOT NULL,
`latitude` DECIMAL(8,6) NULL,
`longitude` DECIMAL(9,6) NULL,
`state` VARCHAR(45) NOT NULL,
`created_date` DATETIME NOT NULL,
`updated_date` DATETIME NOT NULL,
PRIMARY KEY (`address_id`),
CONSTRAINT `FK_STR_STR_ADR` FOREIGN KEY (`address_id`) REFERENCES `store` (`store_address`)
)ENGINE = InnoDB;

How to check if a given data exists in onther table MySql?

I have two tables in MySql Database:
Captain(captain.email)
Members(member.email)
I want when captain table insert data in captain.email then check If members table data in members.email are already exit then data in captain.email not insert in captain table.
How it is possible ?
1.Captain :
CREATE TABLE `captain` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) NOT NULL,
`username_canonical` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`email_canonical` varchar(255) NOT NULL,
`enabled` tinyint(1) NOT NULL,
`salt` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`last_login` datetime DEFAULT NULL,
`locked` tinyint(1) NOT NULL,
`expired` tinyint(1) NOT NULL,
`expires_at` datetime DEFAULT NULL,
`confirmation_token` varchar(255) DEFAULT NULL,
`password_requested_at` datetime DEFAULT NULL,
`roles` longtext NOT NULL COMMENT '(DC2Type:array)',
`credentials_expired` tinyint(1) NOT NULL,
`credentials_expire_at` datetime DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `UNIQ_957A647992FC23A8` (`username_canonical`),
UNIQUE KEY `UNIQ_957A6479A0D96FBF` (`email_canonical`)
)
2.Members :
CREATE TABLE `members` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`team_id` int(11) DEFAULT NULL,
`fos_user_id` int(11) DEFAULT NULL,
`name` varchar(45) DEFAULT NULL,
`email` varchar(45) DEFAULT NULL,
`mobile` varchar(45) DEFAULT NULL,
`role` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `email` (`email`),
UNIQUE KEY `email_2` (`email`),
KEY `IDX_45A0D2FF296CD8AE` (`team_id`),
KEY `IDX_45A0D2FF8C20A0FB` (`fos_user_id`),
CONSTRAINT `FK_45A0D2FF296CD8AE` FOREIGN KEY (`team_id`) REFERENCES `team` (`id`),
CONSTRAINT `FK_45A0D2FF8C20A0FB` FOREIGN KEY (`fos_user_id`) REFERENCES `fos_user` (`id`)
)
There is no way to enforce such constraint.
Using declarative referential integrity (DRI) you could create a table that contains all of the columns that you need to build a unique key on.