MySQL & PHPMyadmin - cannot create relation - mysql

Ok, so I have a database with a number of tables, but I have an issue with two in particular. One is called "asset", and structure is thus:
`assetid` varchar(5) NOT NULL,
`typeid` varchar(2),
`make` varchar(40),
`model` varchar(40),
`serno` varchar(40),
`opsys` varchar(40),
`ownerid` varchar(4)L,
`locid` varchar(4),
`purdate` date,
`insdate` date,
`remdate` date,
`dispdate` date,
`techid` varchar(3)
The other is called "supplier":
`suppid` varchar(3) NOT NULL,
`suppname` varchar(40),
`assetid` varchar(5),
`lastpurdate` date,
In "asset" my PK is assetID. In supplier, I originally had a PK as suppid and assetid. However I could not create a relation linking supplier.assetid to asset.assetid. I was not allowed to do so in PHPMyAdmin, so I deleted assetid from supplier, and added suppid to asset. I want to make suppid a foreign key in asset, but when I try to do so I get this:
#1452 - Cannot add or update a child row: a foreign key constraint fails (`assettracker`.`#sql-15c4_672`, CONSTRAINT `#sql-15c4_672_ibfk_6` FOREIGN KEY (`suppid`) REFERENCES `supplier` (`suppid`) ON DELETE SET NULL ON UPDATE NO ACTION)
Why am I not allowed to do this?

Try this
ALTER TABLE tableName ENGINE = InnoDB;
Does that work?

Related

How to delete from a Table without having to drop a constraint

I have a question in which im required to delete information without dropping or suspending constraints. The question, if allowed to drop constraints is simple. However i am allowed to change Values from NULL to NOT NULL.
DELETE FROM SUPPLIER
WHERE COUNTRY = 'USA';
however another table PRODUCT is the foreign key of a column SUPPLIER_NAME within SUPPLIER. I am not allowed to drop this Constraint.
Ive tried setting the Foreign key to null but it doesnt Work.
EDIT im not allowed to restrict or suspend constraints
this is the full question
"Delete from the database information about all suppliers located in USA. Information about all products supplied by the suppliers located in USA must remain in the database. You are not allowed to drop and/or to suspend any referential integrity constraints and you must modify one of NULL/NOT NULL consistency constraints. "
The tables being used
CREATE TABLE PRODUCT
(
PRODUCT_NAME VARCHAR(40) NOT NULL,
SUPPLIER_NAME VARCHAR(40) NOT NULL,
CATEGORY_NAME VARCHAR(30) NOT NULL,
QUANTITY_PER_UNIT VARCHAR(20),
UNIT_PRICE DECIMAL(10,2) NOT NULL DEFAULT 0,
UNITS_IN_STOCK DECIMAL(9) NOT NULL DEFAULT 0,
UNITS_ON_ORDER DECIMAL(9) NOT NULL DEFAULT 0,
REORDER_LEVEL DECIMAL(9) NOT NULL DEFAULT 0,
DISCONTINUED CHAR(1) NOT NULL DEFAULT 'N',
CONSTRAINT PK_PRODUCT PRIMARY KEY (PRODUCT_NAME),
CONSTRAINT FK_CATEGORY_NAME FOREIGN KEY (CATEGORY_NAME) REFERENCES CATEGORY(CATEGORY_NAME),
CONSTRAINT FK_SUPPLIER_NAME FOREIGN KEY (SUPPLIER_NAME) REFERENCES SUPPLIER(COMPANY_NAME),
CONSTRAINT CK_PRODUCT_UNIT_PRICE CHECK (UNIT_PRICE >= 0),
CONSTRAINT CK_PRODUCT_UNITS_IN_STOCK CHECK (UNITS_IN_STOCK >= 0),
CONSTRAINT CK_PRODUCT_UNITS_ON_ORDER CHECK (UNITS_ON_ORDER >= 0),
CONSTRAINT CK_PRODUCT_REORDER_LEVEL CHECK (REORDER_LEVEL >= 0),
CONSTRAINT CK_PRODUCT_DISCONTINUED CHECK (DISCONTINUED in ('Y','N'))
);
CREATE TABLE SUPPLIER
(
COMPANY_NAME VARCHAR(40) NOT NULL,
CONTACT_NAME VARCHAR(30),
CONTACT_TITLE VARCHAR(30),
ADDRESS VARCHAR(60),
CITY VARCHAR(15),
REGION VARCHAR(15),
POSTAL_CODE VARCHAR(10),
COUNTRY VARCHAR(15),
PHONE VARCHAR(24),
FAX VARCHAR(24),
HOME_PAGE VARCHAR(500),
CONSTRAINT PK_SUPPLIER PRIMARY KEY (COMPANY_NAME)
);
As the foreign key to your PRODUCT table doe not specify an ON DELETE action, it'll have the default behaviour which is RESTRICT. Since you can't update this constraint to SET NULL, you'd probably have to set them NULL yourself.
First, alter the table so the SUPPLIER_NAME foreign key can accept NULL values.
Then, update the PRODUCTS whose supplier are in the USA, set their SUPPLIER_NAME to NULL. Something like this:
update PRODUCT set SUPPLIER_NAME = NULL where SUPPLIER_NAME IN (
select SUPPLIER_NAME from SUPPLIER where COUNTRY = 'USA');
And at last you can then delete the SUPPLIERS with COUNTRY = 'USA'.

Not sure why this syntax error is happening

Hi I'm not very familiar with MySQL as I have only started using it today and I keep getting this syntax error and am not really sure what the problem is. I have attached a screenshot of the code and also pasted it below with the error in bold.
I'm sorry if this is a silly error that is easily fixed I'm just not sure how to fix it and would be very appreciative of any help.
CREATE TABLE copy (
`code` INT NOT NULL,
isbn CHAR(17) NOT NULL,
duration TINYINT NOT NULL,
CONSTRAINT pkcopy PRIMARY KEY (isbn, `code`),
CONSTRAINT fkcopy FOREIGN KEY (isbn) REFERENCES book (isbn));
CREATE TABLE student (
`no` INT NOT NULL,
`name` VARCHAR(30) NOT NULL,
school CHAR(3) NOT NULL,
embargo BIT NOT NULL,
CONSTRAINT pkstudent PRIMARY KEY (`no`));
CREATE TABLE loan (
`code` INT NOT NULL,
`no` INT NOT NULL,
taken DATE NOT NULL,
due DATE NOT NULL,
`return` DATE NULL,
CONSTRAINT pkloan PRIMARY KEY (taken, `code`, `no`),
CONSTRAINT fkloan FOREIGN KEY (`code`, `no`) REFERENCES copy, student **(**`code`, `no`));
Create the tables first, then use the ALTER TABLE statement to add the foreign keys one by one. You won't be able to call two different tables on the foreign key, so you'll have to use an ID that maps to both. Here is an example to add the foreign keys after the table has been created:
Add a new table named vendors and change the products table to include the vendor id field:
USE dbdemo;
CREATE TABLE vendors(
vdr_id int not null auto_increment primary key,
vdr_name varchar(255)
)ENGINE=InnoDB;
ALTER TABLE products
ADD COLUMN vdr_id int not null AFTER cat_id;
To add a foreign key to the products table, you use the following statement:
ALTER TABLE products
ADD FOREIGN KEY fk_vendor(vdr_id)
REFERENCES vendors(vdr_id)
ON DELETE NO ACTION
ON UPDATE CASCADE;

MySQL - error 1215, cannot add foreign key constraint

I know there are numerous questions regarding this error on here but I've searched through many and none seem to explain it in my case!
I've created a table using the following code:
CREATE TABLE Venue (
venueID VARCHAR(20),
venueEmail VARCHAR(30) NOT NULL,
address VARCHAR(100),
phoneNo VARCHAR(20),
managerNo VARCHAR(20),
capacity INT(4),
PRIMARY KEY (venueEmail)
)ENGINE=InnoDB;
And am trying to create a table with a foreign key that refers to the first table using this code:
CREATE TABLE Concert (
referenceNo VARCHAR(6),
venueEmail VARCHAR(30),
eventDate VARCHAR(10),
startTime VARCHAR(5),
ticketsSold INT(4),
PRIMARY KEY (referenceNo),
FOREIGN KEY (venueEmail) REFERENCES Venue ON UPDATE CASCADE ON DELETE CASCADE
)ENGINE=InnoDB;
But it's giving me the 1215 error message!
Syntax wise this isn't correct.
The issue's resolved here:
CREATE TABLE Venue (
venueID VARCHAR(20),
venueEmail VARCHAR(30) NOT NULL,
address VARCHAR(100),
phoneNo VARCHAR(20),
managerNo VARCHAR(20),
capacity INT(4),
PRIMARY KEY (venueEmail)
)ENGINE=InnoDB;
CREATE TABLE Concert (
referenceNo VARCaHAR(6),
venueEmail VARCHAR(30),
eventDate VARCHAR(10),
startTime VARCHAR(5),
ticketsSold INT(4),
PRIMARY KEY (referenceNo),
FOREIGN KEY (venueEmail) REFERENCES Venue(`venueEmail`) ON UPDATE CASCADE ON DELETE CASCADE
)ENGINE=InnoDB;
Note:
The column being referenced should be stated like table_name(column_name).
You missed the column_name part.
REFERENCE
More:
#Bill Karwin added the following useful info in the comment section:
FWIW this is a MySQL idiosyncrasy. In standard SQL, if you omit the
referenced column name, it defaults to the same name as the foreign
key column. But InnoDB doesn't support this shortcut syntax—you must
specify the column in both cases.

sql code is not working in phpmyadmin using mac?

My teacher provided me with this sql code, and I logged in as root into phpmyadmin, added a database called webstore, and then tried to add this code and it's giving me errors. Is there anyone who can tell me what could be causing the errors? I am using a Mac, so I'm not sure if that makes any difference, I can give you a link to dropbox with additional information if necessary.
This is the dropbox link with the code provided (Webstore.sql): https://www.dropbox.com/sh/usfmbeyxqd2q1g5/AADoLFbsz8cL30EC76d60i40a?dl=0
Also, the zip file contains images of the errors I was receiving. PLEASE HELP!!
The SQL statement the error occurs on is
CREATE TABLE Shopping_Cart (
CustID INTEGER NOT NULL,
ProdID INTEGER NOT NULL,
NumOfItems INTEGER,
PRIMARY KEY CLUSTERED (CustID, ProdID)
CONSTRAINT FK_Cust FOREIGN KEY FK_Cat (CustID)
REFERENCES Customers (CustID)
ON DELETE RESTRICT
ON UPDATE RESTRICT,
CONSTRAINT FK_Prod FOREIGN KEY FK_Prod (ProdID)
REFERENCES Products (ProdID)
ON DELETE RESTRICT
ON UPDATE RESTRICT
);
The error reads
A comma or closing bracket was expected. (near "CONSTRAINT" at position 153)
Unexpected beginning of statement. (near "CustID" at position 192)
Unrecognised statement type. (near "REFERENCES" at position 206)
Your PRIMARY KEY line needs a comma after it before the CONSTRAINT.
CREATE TABLE Shopping_Cart (
CustID INTEGER NOT NULL,
ProdID INTEGER NOT NULL,
NumOfItems INTEGER,
PRIMARY KEY CLUSTERED (CustID, ProdID),
CONSTRAINT FK_Cust FOREIGN KEY FK_Cat (CustID)
REFERENCES Customers (CustID)
ON DELETE RESTRICT
ON UPDATE RESTRICT,
CONSTRAINT FK_Prod FOREIGN KEY FK_Prod (ProdID)
REFERENCES Products (ProdID)
ON DELETE RESTRICT
ON UPDATE RESTRICT
);
Edit
It turns out there were a lot of problems with the SQL. The tables were created in the wrong order and the data types were wrong. Here is a rewritten version that I have tested out:
DROP DATABASE IF EXISTS WebStore;
CREATE DATABASE WebStore;
USE WebStore;
CREATE TABLE Categories (
CatID INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
Name VARCHAR(20) NOT NULL,
Descr VARCHAR(120) NOT NULL,
IconURL VARCHAR(64) NOT NULL,
PRIMARY KEY (CatID)
);
CREATE TABLE Products (
ProdID INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
Name VARCHAR(20) NOT NULL,
Category INTEGER UNSIGNED,
Descr VARCHAR(120) NOT NULL,
Price FLOAT NOT NULL,
Stock INTEGER UNSIGNED NOT NULL,
IconURL VARCHAR(64) NOT NULL,
PRIMARY KEY (ProdID),
CONSTRAINT FK_Cat FOREIGN KEY FK_Cat (Category)
REFERENCES Categories (CatID)
ON DELETE RESTRICT
ON UPDATE RESTRICT
);
INSERT INTO Categories VALUES(null,"Laptops","Small computers you can carry","http://localhost/images/laptop.jpg");
SET #laptops := LAST_INSERT_ID();
INSERT INTO Categories VALUES(null,"Desktops","Big computers you cannot carry","http://localhost/images/desktop.jpg");
SET #desktops := LAST_INSERT_ID();
INSERT INTO Categories VALUES(null,"Tablets"," Flat things you lose frequently","http://localhost/images/tablet.jpg");
SET #tablets := LAST_INSERT_ID();
INSERT INTO Products VALUES(null,"DULL 1200",#desktops,"A big dull machine",1290.99,23,"http://localhost/images/dull1200.jpg");
INSERT INTO Products VALUES(null,"8P Totalo",#desktops,"Almost as big as the DULL",990.99,2,"http://localhost/images/8ptotalo.jpg");
INSERT INTO Products VALUES(null,"LaNuveau Bingster",#desktops,"Comes in blue and red",690.99,12,"http://localhost/images/lanuveaubingster.jpg");
INSERT INTO Products VALUES(null,"DULL 122",#laptops,"Small, portable and useless",422.99,4,"http://localhost/images/dull122.jpg");
INSERT INTO Products VALUES(null,"8P Tootsie",#laptops,"Sticky and too heavy",559.99,12,"http://localhost/images/8ptootsie.jpg");
INSERT INTO Products VALUES(null,"LaNuveau Shoobie XT",#laptops,"Weighs a ton but looks sharp",1690.99,122,"http://localhost/images/lanuveaushoobiext.jpg");
INSERT INTO Products VALUES(null,"Motor Roller 12",#tablets,"The only one with a oval screen",422.99,4,"http://localhost/images/mr12.jpg");
INSERT INTO Products VALUES(null,"SamSings OffKey",#tablets,"Needs duct tape to run",559.99,2,"http://localhost/images/samsingsOK.jpg");
INSERT INTO Products VALUES(null,"jPet 12",#tablets,"The first that kinda sorta works",16290.99,722,"http://localhost/images/jpet12.jpg");
CREATE TABLE Customers (
CustID INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
FirstName VARCHAR(40) NOT NULL,
LastName VARCHAR(40) NOT NULL,
Address VARCHAR(60) NOT NULL,
City VARCHAR(40) NOT NULL,
State VARCHAR(20) NOT NULL,
Zip VARCHAR(5) NOT NULL,
PRIMARY KEY (CustID)
);
INSERT INTO Customers VALUES(null,"Gerald","Bostock","1234 TAAB Drive","St. Cleve","FL","12345");
INSERT INTO Customers VALUES(null,"Suzy","Creamcheese","8722 Zappa Road","Paris","TX","75460");
CREATE TABLE Shopping_Cart (
CustID INTEGER UNSIGNED NOT NULL,
ProdID INTEGER UNSIGNED NOT NULL,
NumOfItems INTEGER,
PRIMARY KEY CLUSTERED (CustID, ProdID),
CONSTRAINT FK_Cust FOREIGN KEY FK_Cat (CustID)
REFERENCES Customers (CustID)
ON DELETE RESTRICT
ON UPDATE RESTRICT,
CONSTRAINT FK_Prod FOREIGN KEY FK_Prod (ProdID)
REFERENCES Products (ProdID)
ON DELETE RESTRICT
ON UPDATE RESTRICT
);
INSERT INTO Shopping_Cart VALUES("1","4","2");
INSERT INTO Shopping_Cart VALUES("1","9","1");

MySQL #1005 can't create table, but don't says why, errno:150

I'm making a database, with several tables, and so far I could make the tables, and update it with some demo data, but when a tried to make a new table for connecting two of my tables I just get this can't create table error whatever I did. Tried to rename the entities to an entirely different name maybe that's the problem but it wasn't.
CREATE DATABASE IF NOT EXISTS ETR;
CREATE TABLE Hallgato (
OktAzonosito INT(6) PRIMARY KEY,
EHAazonosito VARCHAR(11),
TeljesNev VARCHAR(50),
Szemelyazonosito INT(6),
AnyaNyelv VARCHAR(20),
VegzettsegSzint VARCHAR(25),
AnyjaNeve VARCHAR(35),
SzuletesiHely VARCHAR(30),
SzuletesiEv DATE,
Allampolgarsag VARCHAR(30),
Neme VARCHAR(5),
Adoazonosito INT(6),
TAJszam INT(6),
BankszamlaSzam INT(9)
) ENGINE = InnoDB;
CREATE TABLE OktAdat (
OktAzonosito INT(6),
NyelvVizsgaNyelve VARCHAR(15),
NyVegzesDatuma DATE,
NyIntezmeny VARCHAR(35),
EgyebVegzetteseg VARCHAR(15),
EgyVegzesDatuma DATE,
ID INT(5) PRIMARY KEY NOT NULL auto_increment,
FOREIGN KEY (OktAzonosito) REFERENCES Hallgato(OktAzonosito) ON DELETE CASCADE
) ENGINE = InnoDB;
CREATE TABLE Oktato (
TEHAazonosito VARCHAR(11) PRIMARY KEY,
Nev VARCHAR(50),
SzuletesiEv DATE,
Szakterulet VARCHAR(25),
Telefonszam INT(9),
Email VARCHAR(50)
) ENGINE = InnoDB;
CREATE TABLE Kurzus (
KurzusKod VARCHAR(8) PRIMARY KEY,
KurzusNev VARCHAR(30),
Idotartam INT(3),
EloadasHelye VARCHAR(25),
Tipus CHAR(3),
Vizsgatipus VARCHAR(7),
KreditErtek INT(2),
OktatoKod VARCHAR(11)
) ENGINE = InnoDB;
CREATE TABLE Terem (
Sorszam INT(3) PRIMARY KEY NOT NULL,
Epuletszam INT(1),
Kapacitas INT(3),
IRszam INT(4),
Utca CHAR(25),
Hazszam INT(2)
) ENGINE = InnoDB;
CREATE TABLE DiakKurz (
kd_id INT (5) PRIMARY KEY NOT NULL auto_increment,
DKKod VARCHAR(8),
EHA VARCHAR(11),
FOREIGN KEY (EHA) REFERENCES Hallgato(EHAazonosito) ON DELETE CASCADE,
FOREIGN KEY (DKKod) REFERENCES Kurzus(KurzusKod) ON DELETE CASCADE
) ENGINE = InnoDB;
The problem is with creating the DiakKurz table.
You'll have to set an INDEX for column EHAazonosito in table Hallgato
CREATE TABLE Hallgato (
OktAzonosito INT(6) PRIMARY KEY,
EHAazonosito VARCHAR(11), INDEX (EHAazonosito),
TeljesNev VARCHAR(50),
Szemelyazonosito INT(6),
AnyaNyelv VARCHAR(20),
VegzettsegSzint VARCHAR(25),
AnyjaNeve VARCHAR(35),
SzuletesiHely VARCHAR(30),
SzuletesiEv DATE,
Allampolgarsag VARCHAR(30),
Neme VARCHAR(5),
Adoazonosito INT(6),
TAJszam INT(6),
BankszamlaSzam INT(9)
) ENGINE = InnoDB;
This
FOREIGN KEY (EHA) REFERENCES Hallgato(EHAazonosito) ON DELETE CASCADE,
doesn't work because EHAazonosito is not the primary key of the Hallgato table. A foreign key can only reference a primary (or unique) key.
Btw: are you awary that the 6 in int(6) is not about limiting the values in the column?
It doesn't do anything. int(6) is the same as int. The 6 is only there to give client applications a hint(!) with how many digits the column should be displayed. It does not enforce anything at all.
Have you tried looking up the error?
If MySQL reports an error number 1005 from a CREATE TABLE statement,
and the error message refers to error 150, table creation failed
because a foreign key constraint was not correctly formed. Similarly,
if an ALTER TABLE fails and it refers to error 150, that means a
foreign key definition would be incorrectly formed for the altered
table. To display a detailed explanation of the most recent InnoDB
foreign key error in the server, issue SHOW ENGINE INNODB STATUS.
http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html
it happened also to me after a dump of the whole schema, what helped was to wrap whole dump within disabled foreign key checks
SET foreign_key_checks=0;
...dump
SET foreign_key_checks=1;