Table definition to a variable - mysql

I want to assign table definition of particular table in to a variable.
I know that, SHOW CREATE TABLE tab_name will return table definition.
I want to assign that definition to a variable.
eg: I have a variable named #tab_def.
When I execute SELECT #tab_def I want to get table definition like
CREATE TABLE `customers` (
`customerNumber` int(11) NOT NULL,
`customerName` varchar(50) NOT NULL,
`contactLastName` varchar(50) NOT NULL,
`contactFirstName` varchar(50) NOT NULL,
`phone` varchar(50) NOT NULL,
`addressLine1` varchar(50) NOT NULL,
`addressLine2` varchar(50) DEFAULT NULL,
`city` varchar(50) NOT NULL,
`state` varchar(50) DEFAULT NULL,
`postalCode` varchar(15) DEFAULT NULL,
`country` varchar(50) NOT NULL,
`salesRepEmployeeNumber` int(11) DEFAULT NULL,
`creditLimit` decimal(10,2) DEFAULT NULL,
PRIMARY KEY (`customerNumber`),
KEY `salesRepEmployeeNumber` (`salesRepEmployeeNumber`),
CONSTRAINT `customers_ibfk_1` FOREIGN KEY (`salesRepEmployeeNumber`) REFERENCES `employees` (`employeeNumber`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Related

customers table wont allow constraint

Hey so im trying to load in my database. The error I get is
CREATE TABLE `customers` (
`customerNumber` int(11) NOT NULL,
`customerName` varchar(50) NOT NULL,
`contactLastName` varchar(50) NOT NULL,
`contactFirstName` varchar(50) NOT NULL,
`phone` varchar(50) NOT NULL,
`addressLine1` varchar(50) NOT NULL,
`addressLine2` varchar(50) DEFAULT NULL,
`city` varchar(50) NOT NULL,
`state` varchar(50) DEFAULT NULL,
`postalCode` varchar(15) DEFAULT NULL,
`country` varchar(50) NOT NULL,
`salesRepEmployeeNumber` int(11) DEFAULT NULL,
`creditLimit` decimal(10,2) DEFAULT NULL,
PRIMARY KEY (`customerNumber`),
KEY `salesRepEmployeeNumber` (`salesRepEmployeeNumber`),
CONSTRAINT `customers_ibfk_1` FOREIGN KEY (`salesRepEmployeeNumber`) REFERENCES `employees` (`employeeNumber`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
MySQL said: Documentation
1215 - Cannot add foreign key constraint
I understand the error but whats the problem its having with the constraint?
Edit:
0
CREATE TABLE `employees` (
`employeeNumber` int(11) NOT NULL,
`lastName` varchar(50) NOT NULL,
`firstName` varchar(50) NOT NULL,
`extension` varchar(10) NOT NULL,
`email` varchar(100) NOT NULL,
`officeCode` varchar(10) NOT NULL,
`reportsTo` int(11) DEFAULT NULL,
`jobTitle` varchar(50) NOT NULL,
PRIMARY KEY (`employeeNumber`),
KEY `reportsTo` (`reportsTo`),
KEY `officeCode` (`officeCode`),
CONSTRAINT `employees_ibfk_1` FOREIGN KEY (`reportsTo`) REFERENCES `employees` (`employeeNumber`),
CONSTRAINT `employees_ibfk_2` FOREIGN KEY (`officeCode`) REFERENCES `offices` (`officeCode`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `offices` (
`officeCode` varchar(10) NOT NULL,
`city` varchar(50) NOT NULL,
`phone` varchar(50) NOT NULL,
`addressLine1` varchar(50) NOT NULL,
`addressLine2` varchar(50) DEFAULT NULL,
`state` varchar(50) DEFAULT NULL,
`country` varchar(50) NOT NULL,
`postalCode` varchar(15) NOT NULL,
`territory` varchar(10) NOT NULL,
PRIMARY KEY (`officeCode`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Ok, you should create the tables in this order:
1.- Your table offices
2.- Your table employees
3.- Your table customers.
The problem is that you are trying to create first the table customers, and it ´s refering a table (employees) that does not exist.

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.

Foreign key won't add

I have these two tables but the foreign key won't add. This is the query I'm using but I keep getting cannot add foreign key error. I have also included the Create table statements. Thanks for any help
ALTER TABLE courses ADD CONSTRAINT fk_fs FOREIGN KEY (teacher1)
REFERENCES teachers(fullName)
CREATE TABLE IF NOT EXISTS `courses` (
`courseID` int(11) NOT NULL AUTO_INCREMENT,
`courseName` varchar(200) DEFAULT NULL,
`module1` varchar(200) DEFAULT NULL,
`module2` varchar(200) DEFAULT NULL,
`module3` varchar(200) DEFAULT NULL,
`module4` varchar(200) DEFAULT NULL,
`teacher1` varchar(200) DEFAULT NULL,
`teacher2` varchar(200) DEFAULT NULL,
`teacher3` varchar(200) DEFAULT NULL,
`teacher4` varchar(200) DEFAULT NULL,
PRIMARY KEY (`courseID`)
)
CREATE TABLE IF NOT EXISTS `teachers` (
`teacherID` int(11) NOT NULL AUTO_INCREMENT,
`userID` int(11) DEFAULT NULL,
`fullName` varchar(200) DEFAULT NULL,
`officeOpen` varchar(5) DEFAULT NULL,
`officeClose` varchar(5) DEFAULT NULL,
`email` varchar(100) DEFAULT NULL,
PRIMARY KEY (`teacherID`)
)
Foreign keys in MySQL must reference indexed columns. I think what you really want to do is add a foreigh-key column to the "courses" table, ex. fkTeacherID column as follows:
CREATE TABLE IF NOT EXISTS `courses` (
`courseID` int(11) NOT NULL AUTO_INCREMENT,
`courseName` varchar(200) DEFAULT NULL,
`module1` varchar(200) DEFAULT NULL,
`module2` varchar(200) DEFAULT NULL,
`module3` varchar(200) DEFAULT NULL,
`module4` varchar(200) DEFAULT NULL,
`teacher1` varchar(200) DEFAULT NULL,
`teacher2` varchar(200) DEFAULT NULL,
`teacher3` varchar(200) DEFAULT NULL,
`teacher4` varchar(200) DEFAULT NULL,
`fkTeacherID` int(11),
PRIMARY KEY (`courseID`)
);
CREATE TABLE IF NOT EXISTS `teachers` (
`teacherID` int(11) NOT NULL AUTO_INCREMENT,
`userID` int(11) DEFAULT NULL,
`fullName` varchar(200) DEFAULT NULL,
`officeOpen` varchar(5) DEFAULT NULL,
`officeClose` varchar(5) DEFAULT NULL,
`email` varchar(100) DEFAULT NULL,
PRIMARY KEY (`teacherID`)
);
ALTER TABLE courses ADD CONSTRAINT fk_fs FOREIGN KEY (fkTeacherID)
REFERENCES teachers(TeacherID)
You can then create a query like:
SELECT fullName
from teachers t
inner join courses c on t.TeacherID = c.fkTeacherID
You can then eliminate the teacher1..4 columns. You may also want to the same with modules. You also eliminate the 4 teachers to a course constraint.
SQLFIDDLE

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

How to optimize a MySQL JOIN Query

I have this MySQL query that I want to optimize:
SELECT r.WarehouseLocation,sum(sir.qty)
FROM repairableissue as r
INNER JOIN SIR ON r.sirno=sir.sirno
AND r.region=sir.region
AND r.ItemName=sir.Itemdesc
AND r.SerialNo=sir.Serialno
WHERE r.status='Pending'
GROUP BY r.warehouseLocation
How do I optimize this query? I read about optimization and found out that indexes might help but still could not achieve the desired performance.
Which index should be used and which should be removed?
Below is the explain of query:
Repairableissue
CREATE TABLE `repairableissue` (
`Vendor` varchar(40) NOT NULL,
`ItemName` varchar(200) NOT NULL,
`SerialNo` varchar(50) NOT NULL,
`person` varchar(200) NOT NULL,
`siteid` varchar(10) NOT NULL,
`invuser` varchar(50) NOT NULL,
`region` varchar(50) NOT NULL,
`id` int(11) NOT NULL AUTO_INCREMENT,
`Dated` date NOT NULL,
`Sirno` varchar(50) NOT NULL,
`status` varchar(30) NOT NULL DEFAULT 'Pending',
`trackthrough` varchar(30) NOT NULL,
`reason` varchar(100) NOT NULL,
`ckh` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`WarehouseType` varchar(20) NOT NULL,
`WarehouseLocation` varchar(20) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`),
KEY `I1` (`status`),
KEY `ind2` (`ItemName`),
KEY `ind3` (`region`),
KEY `ind5` (`SerialNo`),
KEY `ind4` (`Sirno`)
) ENGINE=MyISAM AUTO_INCREMENT=63029 DEFAULT CHARSET=latin1
sir
CREATE TABLE `sir` (
`SirNo` varchar(50) NOT NULL,
`SiteId` varchar(80) NOT NULL,
`Vendor` varchar(70) NOT NULL,
`Type` varchar(15) NOT NULL,
`ItemDesc` varchar(200) NOT NULL,
`ItemCode` varchar(25) NOT NULL,
`SerialNo` varchar(50) NOT NULL,
`Unit` varchar(15) NOT NULL,
`AssetCode` varchar(50) NOT NULL,
`Qty` decimal(11,0) NOT NULL,
`Region` varchar(15) NOT NULL,
`Status` varchar(20) NOT NULL DEFAULT 'Installed',
`FaultInfo` varchar(100) NOT NULL DEFAULT 'date()',
`chk` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`Phase` varchar(15) NOT NULL,
`Category` varchar(200) NOT NULL,
`Issue_Vendor` varchar(30) NOT NULL,
`AssetName` varchar(150) NOT NULL,
`Ownership` varchar(20) NOT NULL,
`Dated` date NOT NULL,
`PersonName` varchar(150) NOT NULL,
`Remarks` varchar(300) NOT NULL,
`po` varchar(100) NOT NULL,
`invuser` varchar(50) NOT NULL,
`id` int(11) NOT NULL AUTO_INCREMENT,
`grnno` varchar(30) NOT NULL,
`WarehouseType` varchar(20) NOT NULL,
`WarehouseLocation` varchar(20) NOT NULL,
`mainpartserial` varchar(200) NOT NULL,
PRIMARY KEY (`Vendor`,`Type`,`ItemCode`,`ItemDesc`,`SerialNo`,`Ownership`,`SirNo`,`Region`,`WarehouseType`,`WarehouseLocation`,`po`,`Qty`,`id`),
KEY `id` (`id`),
KEY `ind4` (`ItemDesc`),
KEY `ind6` (`SerialNo`),
KEY `ind7` (`SerialNo`)
) ENGINE=MyISAM AUTO_INCREMENT=228007 DEFAULT CHARSET=latin1
One multi-column index on r.status + r.warehouseLocation, in that order.
One multi-column index on sir.sirno + sir.region + sir.Itemdesc + sir.Serialno, in order of most cardinality to least cardinality, with sir.qty tacked on the end.
This assumes the fields are small enough to fit (combined) into an index.
Still, join seeks are unavoidable. The number of records that match r.status='Pending' is going to dictate the speed of this query.