MySQL foreign key not found even if it exists - mysql

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%'

Related

How to use "ON UPDATE CASCADE" Correctly in MariaDB 10.1.37 / Ver 15.1?

I am experiencing trouble getting ON UPDATE CASCADE to work with a CONSTRAINT. If I use UPDATE to change the value of customerName in the customer table, it will not change the customerName value in the city table. No error message shows up.
The version of the MariaDB:
Ver 15.1 Distrib 10.1.37-MariaDB
My city table when using SHOW CREATE TABLE city:
city | CREATE TABLE `city` (
`cityId` int(10) unsigned NOT NULL AUTO_INCREMENT,
`city` varchar(50) DEFAULT NULL,
`countryId` int(10) unsigned DEFAULT NULL,
`customerName` varchar(50) DEFAULT NULL,
`address` varchar(50) DEFAULT NULL,
`postalCode` varchar(50) DEFAULT NULL,
`phone` varchar(50) DEFAULT NULL,
`createDate` varchar(50) DEFAULT NULL,
`createdBy` varchar(50) DEFAULT NULL,
`lastUpdateBy` varchar(50) DEFAULT NULL,
PRIMARY KEY (`cityId`),
KEY `customerNameChange01` (`customerName`),
CONSTRAINT `customerNameChange01` FOREIGN KEY (`customerName`)
REFERENCES `customer` (`customerName`)
ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1
My customer table SHOW CREATE TABLE customer:
customer | CREATE TABLE `customer` (
`customerId` int(10) unsigned NOT NULL AUTO_INCREMENT,
`customerName` varchar(50) DEFAULT NULL,
`addressId` int(10) unsigned DEFAULT NULL,
`active` int(10) unsigned DEFAULT NULL,
`address` varchar(50) DEFAULT NULL,
`city` varchar(50) DEFAULT NULL,
`postalCode` varchar(50) DEFAULT NULL,
`phone` varchar(50) DEFAULT NULL,
`createDate` varchar(50) DEFAULT NULL,
`createdBy` varchar(50) DEFAULT NULL,
`lastUpdateBy` varchar(50) DEFAULT NULL,
PRIMARY KEY (`customerId`),
KEY `CustomerName` (`customerName`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1
These are the commands I used to create the index and CONSTRAINT:
CREATE INDEX CustomerName ON customer (customerName);
ALTER TABLE city
ADD CONSTRAINT customerNameChange01
FOREIGN KEY (customerName)
REFERENCES customer (customerName)
ON UPDATE CASCADE
ON DELETE SET NULL;
In the customer table, the CustomerName key references an index. Otherwise, I would not have been able to put in the CONSTRAINT in the city table.
Update: The code works fine in DB Fiddle for MariaDB 10.2 and personal testing confirms that the example code from there works in my own database as well.
Thank you for spending your time.

MySQL 5.7 Windows, table key issue?

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;

MySQL Error Number 150 when creating Table with Foreign Key

I am having an issue creating a new table in my database. I've seen that the error code it is returning is to do with Foreign Key constraints.
I checked to ensure that the data type of the foreign key in the new table matched the data type of the primary key in the other table. They are both int(11).
However I am still getting an error. Am I missing something? This is my SQL script for creating the new table:
CREATE TABLE `regular_features` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(200) DEFAULT NULL,
`day` VARCHAR(200) DEFAULT NULL,
`description` TEXT DEFAULT NULL,
`programme_id` INT(11) NOT NULL,
PRIMARY KEY (`id`),
FOREIGN KEY (`programme_id`) REFERENCES directoryprogramme(id)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
This is the original table containing the primary key:
CREATE TABLE `directoryprogramme` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(250) NOT NULL,
`broadcast_time` VARCHAR(100) NOT NULL,
`description` TEXT NOT NULL,
`days` VARCHAR(150) NOT NULL,
`contributors` VARCHAR(250) NOT NULL,
`directorycompany_id` INT(11) NOT NULL,
`directorycontact_id` VARCHAR(250) NOT NULL,
`facebook_link` VARCHAR(250) DEFAULT NULL,
`twitter_link` VARCHAR(250) DEFAULT NULL,
`wikipedia_link` VARCHAR(250) DEFAULT NULL,
`web` VARCHAR(250) DEFAULT NULL,
`imageextension` VARCHAR(10) DEFAULT NULL,
`type` VARCHAR(20) NOT NULL DEFAULT 'other',
PRIMARY KEY (`id`)
) ENGINE=MYISAM AUTO_INCREMENT=1161 DEFAULT CHARSET=utf8;
The Foreign Key will be the id of directoryprogramme
The problem is the last line of your create statement:
ENGINE=INNODB DEFAULT CHARSET=utf8;
You mix MYISAM in ald table with INNODB in your new table.
That doesn't work.
Chnage the engine in your new table to MYISAM and it works.

Problems with a MySQL server change

I have three tables in MySQL:
CREATE TABLE `mlm`.`facturacion_2012_drm_base` ( `custid`
varchar(20) NOT NULL, `fecha` date NOT NULL, `docid` varchar(20)
NOT NULL, `billid` varchar(20) NOT NULL, `movimiento` varchar(20)
DEFAULT NULL, `movid` varchar(20) DEFAULT NULL, `medio_pago`
varchar(40) DEFAULT NULL, `digitos` varchar(20) DEFAULT NULL,
`monto_facturado` decimal(20,2) NOT NULL, `monto_pagado`
decimal(20,2) NOT NULL, `monto_usado` decimal(20,2) NOT NULL,
`documento` varchar(2) NOT NULL, `codigo_pago` varchar(5) DEFAULT
NULL, `desc_pago` varchar(100) DEFAULT NULL, `sociedad`
varchar(45) DEFAULT NULL, `sociedad_bonif` varchar(45) DEFAULT NULL,
KEY `billid` (`billid`), KEY `motors_no_fact`
(`custid`,`billid`,`fecha`,`documento`) USING BTREE, KEY
`facturacion` (`custid`,`fecha`,`documento`) USING BTREE )
ENGINE=MyISAM DEFAULT CHARSET=latin1 ROW_FORMAT=DYNAMIC;
CREATE TABLE `mlm`.`facturacion_2012_drm_cortes` ( `id` bigint(20)
NOT NULL AUTO_INCREMENT, `fecha_inicial` date NOT NULL,
`fecha_final` date NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM
AUTO_INCREMENT=433 DEFAULT CHARSET=latin1 ROW_FORMAT=DYNAMIC;
CREATE TABLE `mlm`.`facturacion_2012_drm_emitidas` ( `id`
bigint(20) NOT NULL AUTO_INCREMENT, `custid` varchar(20) NOT NULL,
`fecha_emision` date NOT NULL, `id_fechas` bigint(20) NOT NULL,
`monto` decimal(20,2) NOT NULL, `iva` decimal(20,2) NOT NULL,
`total` decimal(20,2) NOT NULL, `medio_pago` varchar(2000) NOT NULL,
`digitos` varchar(100) NOT NULL, `operaciones` int(10) NOT NULL,
`activa` varchar(2) NOT NULL, `movimiento` varchar(45) NOT NULL,
`parcialidades` varchar(100) NOT NULL, `monto_bruto` decimal(20,2)
NOT NULL, `billid` varchar(45) NOT NULL, `serie` varchar(2)
DEFAULT NULL, `folio` int(10) DEFAULT NULL, `uuid` varchar(45)
DEFAULT NULL, PRIMARY KEY (`id`), KEY `motors`
(`billid`,`id_fechas`,`activa`) ) ENGINE=MyISAM AUTO_INCREMENT=511483
DEFAULT CHARSET=latin1;
I changed the MySQL server from 5.1 (32 Bits) to 5.6 (64 Bits) and restored all my tables but I´m having problems with this query:
SELECT a.custid,
a.monto_facturado,
a.billid,
a.fecha,
b.id,
b.fecha_inicial
FROM facturacion_2012_drm_base a,
facturacion_2012_drm_cortes b
WHERE a.custid = ANY (SELECT custid
FROM facturacion_motors_pendientes
WHERE situacion = 'no facturado')
AND a.billid <> ALL (SELECT billid
FROM facturacion_2012_drm_emitidas
WHERE activa = 'SI')
AND a.fecha BETWEEN b.fecha_inicial AND b.fecha_final
AND a.documento = 'FA'
AND Year(a.fecha) = Year(Curdate())
GROUP BY a.billid
Since the server change, the query never finish, showing the message "Query is being executed..."
Anybody knows why this is happening?
At the very least you have indexing problems:
On facturacion_2012_drm_emitidas you filter by activa but do not have an index that can be used for this
On facturacion_2012_drm_base you don't have an index for fecha or documento that can be used
On facturacion_2012_drm_cortes you don't have an index for fecha_inicial or fecha_final
I don't know if you have index problems on facturacion_motors_pendientes because you did not include DDL for it.
Make sure you have the proper indexes for your query and then see what happens. What is happening now is that you have a complex join with subqueries and basically none of it is utilizing indexes, requiring you to execute full table scans on all tables involved.
You also might consider converting these tables to InnoDB, as that is the preferred table type in 5.6. This is of course unless you need certain MyISAM functionality on these tables (like full text search).

MySQL count from one table while joining another

I don't know if it's just been a long day or what, but I cannot figure out the query that I need to run here. We have two tables - One for leads generated and one for reports. The leads table has basic lead info, along with the Source (Campaign) of the lead. However, we need to know the number of leads that an ACCOUNT has received within a date range. Here is the relevant table structure:
client_leads:
id
source
date
client_reports:
account
campaign
date
The 'source' column contains the same values as the 'campaign' column. So, how would I achieve the following:
Say there are 10 leads in the leads table, each with the campaign that generated the lead. There are 10 accounts in the reports table, each with hundreds of campaigns. I need to list each account and how many leads it has in the leads table.
I just can't get the logic straight in my head. I've tried everything that I can think of and it's just not working out for me. If you need further explanation, let me know. I'm trying to describe the problem to the best of my ability.
Edit:
CREATE TABLE `client_leads` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`site_id` int(10) DEFAULT NULL,
`ip` varchar(255) DEFAULT NULL,
`source` varchar(255) DEFAULT NULL,
`kw` varchar(255) DEFAULT NULL,
`adgroup` varchar(255) DEFAULT NULL,
`time` time DEFAULT NULL,
`date` date DEFAULT NULL,
`dayweek` varchar(255) DEFAULT NULL,
`first_name` varchar(255) DEFAULT NULL,
`last_name` varchar(255) DEFAULT NULL,
`address` varchar(255) DEFAULT NULL,
`city` varchar(255) DEFAULT NULL,
`postal_code` char(5) DEFAULT NULL,
`state` char(2) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`preferred_phone` varchar(10) DEFAULT NULL,
`alternate_phone` varchar(10) DEFAULT NULL,
`level_of_education` varchar(255) DEFAULT NULL,
`program_of_interest` varchar(255) DEFAULT NULL,
`organic` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
KEY `site_id` (`site_id`),
KEY `date_indeces` (`time`,`date`,`dayweek`) USING BTREE,
CONSTRAINT `site_id` FOREIGN KEY (`site_id`) REFERENCES `client_sites` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=32 DEFAULT CHARSET=utf8
CREATE TABLE `client_reports` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`account` varchar(255) DEFAULT NULL,
`friendly_name` varchar(255) DEFAULT NULL,
`sites_id` int(10) DEFAULT NULL,
`service` varchar(255) DEFAULT NULL,
`date` date DEFAULT NULL,
`campaign` varchar(255) DEFAULT NULL,
`adgroup` varchar(255) DEFAULT NULL,
`keyword` varchar(255) DEFAULT NULL,
`impressions` int(10) DEFAULT NULL,
`clicks` int(10) DEFAULT NULL,
`cost` float DEFAULT NULL,
`max_cpc` float DEFAULT NULL,
`avg_pos` float DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `stats` (`impressions`,`clicks`,`cost`),
KEY `date` (`date`),
KEY `campaign` (`campaign`),
KEY `adgroup` (`adgroup`),
KEY `keyword` (`keyword`),
KEY `service` (`service`),
KEY `sites_id` (`sites_id`),
CONSTRAINT `sites_id` FOREIGN KEY (`sites_id`) REFERENCES `client_sites` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=109167 DEFAULT CHARSET=utf8
Edit Again:
client_reports table data viewable at http://pastebin.com/T532W3Eq
client_leads table data viewable at http://pastebin.com/9cjWEvck
SELECT cr.account, cr.campaign, cr.date, COUNT(cl.id) AS number_of_leads
FROM client_reports cr
LEFT JOIN client_leads cl
ON cl.source = cr.campaign
GROUP BY cl.source