Error Code 1452 When attempting to Alter Table Constraint - mysql

ALTER TABLE `charter`
ADD CONSTRAINT `charter_ibfk_3` FOREIGN KEY (`CHAR_DESTINATION`)
REFERENCES `airport` (`AIRPORT_CODE`);
I am attempting to create this relationship:
Charter and Airport ERD Diagram
CREATE TABLE `antonellacammarota` (
`CUS_CODE` int(6) NOT NULL DEFAULT '0',
PRIMARY KEY (`CUS_CODE`),
FOREIGN KEY (`CUS_CODE`) REFERENCES `CUSTOMER` (`CUS_CODE`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
insert into customer values (10076, "Cammarota", "Antonella", "T", "805", "555-1212", 0);
insert into antonellacammarota(select cus_code from customer where cus_lname = 'Cammarota');
--
-- Table structure for table `airport`
--
CREATE TABLE IF NOT EXISTS `airport` (
`AIRPORT_CODE` varchar(3) NOT NULL DEFAULT '0',
`AIRPORT_NAME` varchar(40) DEFAULT NULL,
`AIRPORT_ADDRESS` varchar(45) DEFAULT NULL,
`AIRPORT_CITY` varchar(25) DEFAULT NULL,
`AIRPORT_STATE` char(2) DEFAULT NULL,
`AIRPORT_ZIP` varchar(10) DEFAULT NULL,
`AIRPORT_COUNTRY` varchar(25) DEFAULT NULL,
`AIRPORT_AREACODE` varchar(3) DEFAULT NULL,
`AIRPORT_PHONE` varchar(8) DEFAULT NULL,
PRIMARY KEY (`AIRPORT_CODE`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Constraints for table `airport`
--
ALTER TABLE `charter`
ADD CONSTRAINT `charter_ibfk_3` FOREIGN KEY (`CHAR_DESTINATION`) REFERENCES `airport` (`AIRPORT_CODE`);
--
-- Dumping data for table `airport`
--
INSERT INTO `airport` (`AIRPORT_CODE`, `AIRPORT_NAME`, `AIRPORT_ADDRESS`, `AIRPORT_CITY`, `AIRPORT_STATE`,
`AIRPORT_ZIP`, `AIRPORT_COUNTRY`, `AIRPORT_AREACODE`, `AIRPORT_PHONE`) VALUES
('ATL', 'Hartsfield-Jackson Atlanta Int', '6000 N Terminal Pkwy.', 'Atlanta', 'GA', '30320', 'US', '808', '897-1910'),
('BNA', 'Nashville Int', '1 Terminal Dr.', 'Nashville', 'TN', '37214', 'US', '615', '275-1675'),
('GNV', 'Gainesville Regional', '3880 NE 39th Ave.', 'Gainesville', 'FL', '32609', 'US', '352', '373-0249'),
('MOB', 'Mobile Regional', '8400 Airport Blvd.', 'Mobile', 'AL', '36608', 'US', '800', '357-5373'),
('MOY', 'Monterrey', '', 'Monterrey', '', '', 'Columbia', '', ''),
('STL', 'St. Louis Lambert Int', '10701 Lambert International Blvd.', 'St. Louis', 'MO', '63145', 'US', '314', '426-8000'),
('TYS', 'McGhee Tyson', '2055 Alcoa Hwy', 'Alcoa', 'TN', '37701', 'US', '865', '345-3000');

Use this to find out what entry is screwing things up
SELECT CHAR_TRIP, CHAR_DESTINATION
FROM charter
WHERE CHAR_DESTINATION NOT IN (
SELECT AIRPORT_CODE FROM airport);

Related

error of 1824: failed to open the referenced table

Not sure what i'm doing wrong here. Im trying to understand the relationships between tables? Please help thank you
DROP DATABASE IF EXISTS `sql_retail`;
CREATE DATABASE `sql_retail`;
USE `sql_retail`;
SET NAMES utf8 ;
SET character_set_client = utf8mb4 ;
CREATE TABLE `RETAIL_ORDER` (
`OrderNumber` int(4) NOT NULL,
`StoreNumber` int(2) NOT NULL,
`StoreZip` char(9) NOT NULL,
`OrderMonth` char(12) NOT NULL,
`OrderYear` int(4) NOT NULL,
`OrderTotal` float(10) NOT NULL,
PRIMARY KEY (`OrderNumber`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO `RETAIL_ORDER` VALUES (1000, 10, 98110, 'December', 2017, 445.00);
INSERT INTO `RETAIL_ORDER` VALUES (2000, 20, 02335, 'December', 2017, 310.00);
INSERT INTO `RETAIL_ORDER` VALUES (3000, 10, 98110, 'January', 2018, 480.00);
CREATE TABLE `ORDER_ITEM` (
`OrderNumber` int(11) NOT NULL,
`SKU` int(7) NOT NULL,
`Quantity` int(6) NOT NULL,
`Price` float(10) NOT NULL,
`Extended Price` float(10) NOT NULL,
PRIMARY KEY (`OrderNumber`),FOREIGN KEY(`OrderNumber`)REFERENCES RETAIL_ORDER(`OrderNumber`),
FOREIGN KEY(`SKU`)REFERENCES SKU_DATA(`SKU`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO `ORDER_ITEM` VALUES (1000, 201000, 1, 300.00, 300.00);
INSERT INTO `ORDER_ITEM` VALUES (1000, 202000, 1, 130.00, 130.00);
INSERT INTO `ORDER_ITEM` VALUES (2000, 101100, 4, 50.00, 200.00);
INSERT INTO `ORDER_ITEM` VALUES (2000, 101200, 2, 50.00, 100.00);
INSERT INTO `ORDER_ITEM` VALUES (3000, 100200, 1, 300.00, 300.00);
INSERT INTO `ORDER_ITEM` VALUES (3000, 101100, 2, 50.00, 100.00);
INSERT INTO `ORDER_ITEM` VALUES (3000, 101200, 1, 50.00, 50.00);
CREATE TABLE `SKU_DATA` (
`SKU` int(11) NOT NULL,
`SKU_Description` varchar(50) NOT NULL,
`Department` varchar(20) NOT NULL,
`Buyer` varchar(15) NOT NULL,
PRIMARY KEY (`SKU`),FOREIGN KEY(`Buyer`)REFERENCES BUYER(`BuyerName`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO `SKU_DATA` VALUES (100100, 'Std. Scuba Tank, Yellow', 'Water Sports', 'Peter Hansen');
INSERT INTO `SKU_DATA` VALUES (100200, 'Std. Scuba Tank, Magenta', 'Water Sports', 'Peter Hansen');
INSERT INTO `SKU_DATA` VALUES (100300, 'Std. Scuba Tank, Light Blue', 'Water Sports', 'Peter Hansen');
INSERT INTO `SKU_DATA` VALUES (100400, 'Std. Scuba Tank, Dark Blue', 'Water Sports', 'Peter Hansen');
INSERT INTO `SKU_DATA` VALUES (100500, 'Std. Scuba Tank, Light Green', 'Water Sports', 'Peter Hansen');
INSERT INTO `SKU_DATA` VALUES (100600, 'Std. Scuba Tank, Dark Green', 'Water Sports', 'Peter Hansen');
INSERT INTO `SKU_DATA` VALUES (101100, 'Dive Mask, Small Clear', 'Water Sports', 'Nancy Meyers');
INSERT INTO `SKU_DATA` VALUES (101200, 'Dive Mask, Med Clear', 'Water Sports', 'Nancy Meyers');
INSERT INTO `SKU_DATA` VALUES (201000, 'Half dome tent', 'camping', 'Cindy Lo');
INSERT INTO `SKU_DATA` VALUES (202000, 'Half dome tent vestibule', 'camping', 'Cindy Lo');
INSERT INTO `SKU_DATA` VALUES (203000, 'Half dome tent vestibule wide', 'camping', 'Cindy Lo');
INSERT INTO `SKU_DATA` VALUES (301000, 'Light fly climbing harness', 'climbing', 'Jerry Martin');
INSERT INTO `SKU_DATA` VALUES (302000, 'Locking Carabiner, Oval', 'climbing', 'Jerry Martin');
CREATE TABLE `BUYER` (
`BuyerName` varchar(15) NOT NULL,
`Department` varchar(15) NOT NULL,
`Position` varchar(15) NOT NULL,
`Supervisor` varchar(15) NOT NULL,
PRIMARY KEY (`BuyerName`),FOREIGN KEY(`Supervisor`)REFERENCES BUYER(`BuyerName`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO `SKU_DATA` VALUES ('Cindy Lo', 'Purchasing', 'Buyer 2', 'Mary Smith');
INSERT INTO `SKU_DATA` VALUES ('Jerry Martin', 'Purchasing', 'Buyer 1', 'Cindo Lo');
INSERT INTO `SKU_DATA` VALUES ('Mary Smith', 'Purchasing', 'Manager','' );
INSERT INTO `SKU_DATA` VALUES ('Nancy Meyers', 'Purchasing', 'Buyer 1', 'Pete Hansen');
INSERT INTO `SKU_DATA` VALUES ('Pete Hansen', 'Purchasing', 'Buyer 3', 'Mary Smith');
You have some errors.
First you assign a foreign key to a table that don't exists yet and second you have duplicate values into your inserts for your primary keys.
I have fixed your table creation, check your insert datas.
Follow below approach to create your tables and then do the inserts:
DROP DATABASE IF EXISTS sql_retail ;
CREATE DATABASE sql_retail ;
USE sql_retail ;
SET NAMES utf8 ;
SET character_set_client = utf8mb4 ;
CREATE TABLE `RETAIL_ORDER` (
`OrderNumber` int(4) NOT NULL,
`StoreNumber` int(2) NOT NULL,
`StoreZip` char(9) NOT NULL,
`OrderMonth` char(12) NOT NULL,
`OrderYear` int(4) NOT NULL,
`OrderTotal` float(10) NOT NULL,
PRIMARY KEY (`OrderNumber`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
CREATE TABLE `ORDER_ITEM` (
`OrderNumber` int(11) NOT NULL,
`SKU` int(7) NOT NULL,
`Quantity` int(6) NOT NULL,
`Price` float(10) NOT NULL,
`Extended Price` float(10) NOT NULL,
PRIMARY KEY (`OrderNumber`),
FOREIGN KEY(`OrderNumber`)REFERENCES RETAIL_ORDER(`OrderNumber`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
CREATE TABLE `SKU_DATA` (
`SKU` int(11) NOT NULL,
`SKU_Description` varchar(50) NOT NULL,
`Department` varchar(20) NOT NULL,
`Buyer` varchar(15) NOT NULL,
PRIMARY KEY (`SKU`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
ALTER TABLE ORDER_ITEM ADD FOREIGN KEY(`SKU`)REFERENCES SKU_DATA(`SKU`);
CREATE TABLE `BUYER` (
`BuyerName` varchar(15) NOT NULL,
`Department` varchar(15) NOT NULL,
`Position` varchar(15) NOT NULL,
`Supervisor` varchar(15) NOT NULL,
PRIMARY KEY (`BuyerName`),
FOREIGN KEY(`Supervisor`)REFERENCES BUYER(`BuyerName`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
ALTER TABLE SKU_DATA ADD FOREIGN KEY(`Buyer`)REFERENCES BUYER(`BuyerName`);
Demo: https://www.db-fiddle.com/f/7yUJcuMJPncBBnrExKbzYz/28

Adding Foreign Key Error

I want to add a foreign key from Table Customers, row= "Customer ID" to Table Pet, row= "Customer ID".
-- Table structure for table `Customers`
CREATE TABLE IF NOT EXISTS `Customers` (
`CustomerID` varchar(50) NOT NULL,
`Fname` varchar(50) DEFAULT NULL,
`LName` varchar(20) DEFAULT NULL,
`Tel` varchar(20) DEFAULT NULL,
`Fax` varchar(20) DEFAULT NULL,
`CustType` varchar(20) DEFAULT NULL,
`AdState` varchar(50) DEFAULT NULL,
`City` varchar(20) DEFAULT NULL,
`Zip` varchar(20) DEFAULT NULL,
`Street` varchar(20) DEFAULT NULL,
PRIMARY KEY (`CustomerID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- Dumping data for table `Customers`
INSERT INTO `Customers` (`CustomerID`, `Fname`, `LName`, `Tel`, `Fax`, `CustType`, `AdState`, `City`, `Zip`, `Street`) VALUES
('AC001', 'All', 'Creatures', '206 555-6622', '206 555-7854', '2', 'WA', 'Tall Pines', '98746', '21 Grace St.'),
('AD001', 'Johnathan', 'Adams', '206 555 7623', '206 555 8855', '1', 'WA', 'Mountain View', '984101012', '66 10th St'),
('AD002', 'William', 'Adams', '503 555 7623', '503 555 7319', '1', 'OR', 'Lakewille', '9740110011', '1122 10th_St'),
('AK001', 'Animal', 'Kingdom', '208 555 7108', '', '2', 'ID', 'Borderville', '834835646', '15 Marlin Lane');
CREATE TABLE IF NOT EXISTS `Pet` (
`ID` varchar(50) NOT NULL,
`CustomerID` varchar(50) NOT NULL,
`Gender` varchar(20) DEFAULT NULL,
`Race` varchar(20) DEFAULT NULL,
`Name` varchar(20) DEFAULT NULL,
`Kind` varchar(20) DEFAULT NULL,
`Birthday` varchar(20) DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- Dumping data for table `Pet`
INSERT INTO `Pet` (`ID`, `CustomerID`, `Gender`, `Race`, `Name`, `Kind`, `Birthday`) VALUES
('AC001-01', '0', 'M', 'Long Ear', 'Bobo', 'Rabbit', '4/8/92'),
('AC001-02', '0', 'F', 'Chameleon', 'Presto Chango', 'Lizard', '5/1/92'),
('AC001-03', '0', 'M', '', 'Stinky', 'Skunk', '8/1/91'),
('AC001-04', '0', 'M', 'German Shepherd', 'Fido', 'Dog', '6/1/90'),
('AD001-01', '0', 'F', 'Potbelly', 'Patty', 'Pig', '2/15/91'),
('AD001-02', '0', 'M', 'Palomino', 'Rising Sun', 'Horse', '4/10/90'),
('AD002-01', '0', 'F', 'Mixed', 'Dee Dee', 'Dog', '2/15/91'),
('AK001-03', '0', 'M', '', 'Jerry', 'Rat', '2/1/88'),
('AK001-07', '0', 'M', 'Beagle', 'Luigi', 'Dog', '8/1/92');
This is the code that I have been using to add the foreign key:
ALTER TABLE Pet ADD CONSTRAINT Pet_FK
FOREIGN KEY (CustomerID) REFERENCES Customers (CustomerID);
And the error message from this is:
#1452 - Cannot add or update a child row: a foreign key constraint fails
(`hospital`.`#sql-523_76e`, CONSTRAINT `Pet_FK` FOREIGN KEY (`CustomerID`)
REFERENCES `Customers` (`CustomerID`))
I am quite a beginner with database and I have no idea what I should try next.
I think that's all. Im still new to this stackoverflow so if I missed any necessary information please tell me and I will add it.
UPDATE***
ALTER TABLE Customers ADD CONSTRAINT Customers_FK
FOREIGN KEY (CustomerID) REFERENCES Pet (CustomerID);
I swapped some positions and the error code I recieve is:
#1215 - Cannot add foreign key constraint
Simple one.
There is an row that contains the CustomerID that can't be matched. So first you need to remove/edit/handle the entry and than add a foreign key.
The CustomerID you're trying to enter in PETS table, does not exist in CUSTOMERS table, and that is why your Foreign Key constraint fails and throws error.
You need to ensure that the CustomerIDs you're entering in your Pets table, exist in Customers table OR simply insert NULL in the PETS.CUSTOMERID field
Enterx is right.
For being able to detect not matching row :
SELECT * FROM Pet p WHERE (SELECT COUNT(*) FROM Customers c WHERE c.CustomerID=p.CustomerID)=0
Just change SELECT * by DELETE for deleting missmatching Pet entry.
You can UPDATE Pet.CustomerID to NULL too. But you have to define CustomerID, from Pet table, with NULL option (and not NOT NULL)
It looks like to me that you inserted values in table Pet's column ID when they should have been inserted in CustomerID and vice-versa.
By the way, it's not really good to have IDs as VARCHARs, specially when they are foreign keys. This makes queries processing slower, although your tables don't look like they'll have a huge number of rows for this to make a difference. Anyway, it's just an observation. I would consider have artificial int primary keys in my tables.
EDIT
I had misread table Pet's values. The other answers here are right. You need to update those 0 values in CustomerID column to match existing CustomerIDs in Customer table or delete them, otherwise you'll get an error when trying to create the FK.
try this
CREATE TABLE IF NOT EXISTS `Pet` (
`ID` varchar(50) NOT NULL,
FOREIGN KEY (`CustomerID`) REFERENCES Customers(CustomerID) varchar(50) NOT NULL,
`Gender` varchar(20) DEFAULT NULL,
`Race` varchar(20) DEFAULT NULL,
`Name` varchar(20) DEFAULT NULL,
`Kind` varchar(20) DEFAULT NULL,
`Birthday` varchar(20) DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

The way foreign keys work when there are 3 tables dependent on each other

I have tables
items
products
brands
their contents:
products:
- samsung galaxy s2
- iphone 5
brands
- samsung
- apple
the difference between an item and a product is as follows:
product is lets say iPhone.
item is a certain user's certain iPhone with its own properties like color and purchase price.
the product iPhone has a brand/manufacturer of Apple.
when inserting a new item, I want the database to get the brand from the product the item belongs to, so my foreign key is set up like this:
'db_name`.'products'.`productBrand`
I have two brands ATM - Samsung and Apple.
When I try to insert a new item via phpMyAdmin's interface and I get to the itemBrand column, the dropdown field only allows me one option - 1 (Samsung), no matter if I've chosen product 1 or 2 (Samsung Galaxy or iPhone5) at the itemGenericProduct column.
What am I doing wrong?
Here is some more detailed info:
CREATE TABLE IF NOT EXISTS `brands` (
`brandId` int(11) NOT NULL AUTO_INCREMENT,
`brandName` varchar(30) NOT NULL,
`brandLogo` varchar(100) NOT NULL,
`brandDescription` text NOT NULL,
PRIMARY KEY (`brandId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;
--
-- Dumping data for table `brands`
--
INSERT INTO `brands` (`brandId`, `brandName`, `brandLogo`, `brandDescription`) VALUES
(1, 'Samsung', '', 'Manufacturer of ...'),
(2, 'Apple', '', 'American high-tech company ...');
--
-- Table structure for table `items`
--
CREATE TABLE IF NOT EXISTS `items` (
`itemId` int(11) NOT NULL AUTO_INCREMENT,
`generalProductId` int(11) NOT NULL,
`itemPurchasedPrice` double NOT NULL,
`itemDateAdded` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`itemDescription` text,
`itemBrand` int(11) NOT NULL,
`itemBoughtFromPlace` int(11) NOT NULL,
`itemBoughtFromUser` int(11) NOT NULL,
`itemConditionNew` tinyint(1) NOT NULL DEFAULT '1',
`itemBeingSold` tinyint(1) NOT NULL DEFAULT '1',
`itemSellPrice` double DEFAULT NULL,
PRIMARY KEY (`itemId`),
KEY `generalProductId` (`generalProductId`),
KEY `itemBrand` (`itemBrand`),
KEY `itemBoughtFromPlace` (`itemBoughtFromPlace`),
KEY `itemBoughtFromUser` (`itemBoughtFromUser`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
--
-- Table structure for table `products`
--
CREATE TABLE IF NOT EXISTS `products` (
`productId` int(11) NOT NULL AUTO_INCREMENT,
`productName` varchar(200) NOT NULL,
`productTimeAdded` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`productDescription` text,
`productBrand` int(11) NOT NULL,
`productFirstAddedFrom` int(11) NOT NULL,
`productAvatar` varchar(100) DEFAULT NULL,
PRIMARY KEY (`productId`),
KEY `productBrand` (`productBrand`,`productFirstAddedFrom`),
KEY `productFirstAddedFrom` (`productFirstAddedFrom`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=5 ;
--
-- Dumping data for table `products`
--
INSERT INTO `products` (`productId`, `productName`, `productTimeAdded`, `productDescription`, `productBrand`, `productFirstAddedFrom`, `productAvatar`) VALUES
(3, 'Samsung Galaxy SII', '2013-10-26 07:46:08', 'The Samsung Galaxy S II is a .....', 1, 1, NULL),
(4, 'iPhone 5', '2013-10-26 07:46:08', 'The iPhone 5 is a ....', 1, 2, NULL);
EDIT:
the following lines in PRODUCTS table seem strange
KEY `productBrand` (`productBrand`,`productFirstAddedFrom`),
KEY `productFirstAddedFrom` (`productFirstAddedFrom`)
because in the visual layout they look this way:
Foreign keys must point at a column of an other table (which has to be the same (ex.: INT(11) - INT(11)).
When your tables are created, you can add a foreign key by using
ALTER TABLE mytable ADD FOREIGN KEY (myfkey) REFERENCES myothertable(parentkey)
Now if we apply it to your structure:
DROP TABLE items; DROP TABLE brands; DROP TABLE products;
CREATE TABLE IF NOT EXISTS `brands` (
`brandId` int(11) NOT NULL AUTO_INCREMENT,
`brandName` varchar(30) NOT NULL,
`brandLogo` varchar(100) NOT NULL,
`brandDescription` text NOT NULL,
PRIMARY KEY (`brandId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;
INSERT INTO `brands` (`brandId`, `brandName`, `brandLogo`, `brandDescription`) VALUES
(1, 'Samsung', '', 'Manufacturer of ...'),
(2, 'Apple', '', 'American high-tech company ...');
CREATE TABLE IF NOT EXISTS `items` (
`itemId` int(11) NOT NULL AUTO_INCREMENT,
`generalProductId` int(11) NOT NULL,
`itemPurchasedPrice` double NOT NULL,
`itemDateAdded` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`itemDescription` text,
`itemBrand` int(11) NOT NULL,
`itemBoughtFromPlace` int(11) NOT NULL,
`itemBoughtFromUser` int(11) NOT NULL,
`itemConditionNew` tinyint(1) NOT NULL DEFAULT '1',
`itemBeingSold` tinyint(1) NOT NULL DEFAULT '1',
`itemSellPrice` double DEFAULT NULL,
PRIMARY KEY (`itemId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
CREATE TABLE IF NOT EXISTS `products` (
`productId` int(11) NOT NULL AUTO_INCREMENT,
`productName` varchar(200) NOT NULL,
`productTimeAdded` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`productDescription` text,
`productBrand` int(11) NOT NULL,
`productFirstAddedFrom` int(11) NOT NULL,
`productAvatar` varchar(100) DEFAULT NULL,
PRIMARY KEY (`productId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=5 ;
INSERT INTO `products` (`productId`, `productName`, `productTimeAdded`, `productDescription`, `productBrand`, `productFirstAddedFrom`, `productAvatar`) VALUES
(3, 'Samsung Galaxy SII', '2013-10-26 07:46:08', 'The Samsung Galaxy S II is a .....', 1, 1, NULL),
(4, 'iPhone 5', '2013-10-26 07:46:08', 'The iPhone 5 is a ....', 1, 2, NULL);
ALTER TABLE items ADD FOREIGN KEY(generalProductId) REFERENCES products(productId) ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE products ADD FOREIGN KEY(productBrand) REFERENCES brands(brandId) ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE items ADD FOREIGN KEY(itemBrand) REFERENCES product(productBrand) ON DELETE CASCADE ON UPDATE CASCADE;
If you want to keep the brandID stored in the items table, the foreign key constarint has to be a composite one (and a Unique index added to products in order for that to work):
Table brands:
CREATE TABLE IF NOT EXISTS `brands` (
`brandId` int(11) NOT NULL AUTO_INCREMENT,
`brandName` varchar(30) NOT NULL,
`brandLogo` varchar(100) NOT NULL,
`brandDescription` text NOT NULL,
PRIMARY KEY (`brandId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;
INSERT INTO `brands` (`brandId`, `brandName`, `brandLogo`, `brandDescription`)
VALUES
(1, 'Samsung', '', 'Manufacturer of ...'),
(2, 'Apple', '', 'American high-tech company ...');
Table products:
CREATE TABLE IF NOT EXISTS `products` (
`productId` int(11) NOT NULL AUTO_INCREMENT,
`productName` varchar(200) NOT NULL,
`productTimeAdded` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`productDescription` text,
`productBrand` int(11) NOT NULL,
`productFirstAddedFrom` int(11) NOT NULL,
`productAvatar` varchar(100) DEFAULT NULL,
PRIMARY KEY (`productId`),
KEY `productBrand` (`productBrand`,`productFirstAddedFrom`),
KEY `productFirstAddedFrom` (`productFirstAddedFrom`),
FOREIGN KEY (productBrand) -- FK added
REFERENCES brands (brandId),
UNIQUE (productBrand, productId) -- Unique index added
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;
INSERT INTO `products`
(`productId`, `productName`, `productTimeAdded`, `productDescription`,
`productBrand`, `productFirstAddedFrom`, `productAvatar`)
VALUES
(3, 'Samsung Galaxy SII', '2013-10-26 07:46:08', 'The Samsung Galaxy S II is a .....', 1, 1, NULL),
(4, 'iPhone 5', '2013-10-26 07:46:08', 'The iPhone 5 is a ....', 1, 2, NULL);
Table items:
CREATE TABLE IF NOT EXISTS `items` (
`itemId` int(11) NOT NULL AUTO_INCREMENT,
`generalProductId` int(11) NOT NULL,
`itemPurchasedPrice` double NOT NULL,
`itemDateAdded` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`itemDescription` text,
`itemBrand` int(11) NOT NULL,
`itemBoughtFromPlace` int(11) NOT NULL,
`itemBoughtFromUser` int(11) NOT NULL,
`itemConditionNew` tinyint(1) NOT NULL DEFAULT '1',
`itemBeingSold` tinyint(1) NOT NULL DEFAULT '1',
`itemSellPrice` double DEFAULT NULL,
PRIMARY KEY (`itemId`),
KEY `generalProductId` (`generalProductId`),
KEY `itemBrand` (`itemBrand`),
KEY `itemBoughtFromPlace` (`itemBoughtFromPlace`),
KEY `itemBoughtFromUser` (`itemBoughtFromUser`),
FOREIGN KEY (itemBrand, generalProductId) -- composite FK
REFERENCES products (productBrand, productId)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;

Get 10 latest post

I prepare a sql query to get the most current topics of a simple forum, and I have the following provision:
CREATE TABLE IF NOT EXISTS `f_categoria` (
`id_categoria` int(4) NOT NULL,
`name` varchar(20) NOT NULL,
`desc` varchar(50) NOT NULL,
`id_foro` int(3) NOT NULL,
`estado` int(1) NOT NULL,
`visibilidad` int(2) NOT NULL,
PRIMARY KEY (`id_categoria`),
KEY `id_categoria` (`id_categoria`),
KEY `id_foro` (`id_foro`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `f_categoria` (`id_categoria`, `name`, `desc`, `id_foro`, `estado`, `visibilidad`) VALUES
(1, 'Programacion', 'Programacion', 1, 1, 1),
(2, 'Modelado', 'Modeladoen 3d', 1, 1, 1);
-- --------------------------------------------------------
CREATE TABLE IF NOT EXISTS `f_comentario` (
`id_comentario` bigint(20) NOT NULL AUTO_INCREMENT,
`id_post` bigint(20) NOT NULL,
`id_user` bigint(20) NOT NULL,
`contenido` longtext NOT NULL,
`number` int(4) NOT NULL,
`fecha` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id_comentario`),
KEY `id_post` (`id_post`),
KEY `id_user` (`id_user`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=4 ;
INSERT INTO `f_comentario` (`id_comentario`, `id_post`, `id_user`, `contenido`, `number`, `fecha`) VALUES
(1, 1, 1, 'Este es el primer comentario', 1, '2013-07-30 23:12:53'),
(2, 1, 1, 'Este es el comentario 2', 2, '2013-07-30 23:25:12'),
(3, 2, 1, 'cOMENTARIO EN EL POST2', 1, '2013-07-30 23:53:44');
-- --------------------------------------------------------
CREATE TABLE IF NOT EXISTS `f_foro` (
`id_foro` int(5) NOT NULL,
`name` varchar(15) NOT NULL,
`desc` varchar(50) NOT NULL,
`visibilidad` int(2) NOT NULL,
PRIMARY KEY (`id_foro`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `f_foro` (`id_foro`, `name`, `desc`, `visibilidad`) VALUES
(1, 'Prueba', 'Foro de prueba', 1);
-- --------------------------------------------------------
CREATE TABLE IF NOT EXISTS `f_post` (
`id_post` bigint(20) NOT NULL AUTO_INCREMENT,
`id_user` bigint(20) NOT NULL,
`titulo` varchar(50) NOT NULL,
`contenido` longtext NOT NULL,
`fecha` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`estado` int(1) NOT NULL,
`id_categoria` int(4) NOT NULL,
PRIMARY KEY (`id_post`),
KEY `id_user` (`id_user`),
KEY `id_categoria` (`id_categoria`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=4 ;
INSERT INTO `f_post` (`id_post`, `id_user`, `titulo`, `contenido`, `fecha`, `estado`, `id_categoria`) VALUES
(1, 1, '¡Hola!', 'mensaje de prueba', '2013-07-30 23:12:05', 1, 1),
(2, 1, 'post 2', 'es el post2', '2013-07-30 23:27:25', 1, 2),
(3, 1, 'post3', 'el post3', '2013-07-31 00:04:52', 1, 1);
-- --------------------------------------------------------
CREATE TABLE IF NOT EXISTS `f_user` (
`id_user` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(15) NOT NULL,
`mail` varchar(50) NOT NULL,
`fecha` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id_user`),
UNIQUE KEY `name` (`name`,`mail`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ;
--
-- Volcado de datos para la tabla `f_user`
--
INSERT INTO `f_user` (`id_user`, `name`, `mail`, `fecha`) VALUES
(1, 'tulipo', 'f673150#rmqkr.net', '2013-07-30 23:07:36');
ALTER TABLE `f_categoria`
ADD CONSTRAINT `f_categoria_ibfk_1` FOREIGN KEY (`id_foro`) REFERENCES `f_foro` (`id_foro`);
ALTER TABLE `f_comentario`
ADD CONSTRAINT `f_comentario_ibfk_2` FOREIGN KEY (`id_user`) REFERENCES `f_user` (`id_user`),
ADD CONSTRAINT `f_comentario_ibfk_1` FOREIGN KEY (`id_post`) REFERENCES `f_post` (`id_post`);
ALTER TABLE `f_post`
ADD CONSTRAINT `f_post_ibfk_2` FOREIGN KEY (`id_categoria`) REFERENCES `f_categoria` (`id_categoria`),
ADD CONSTRAINT `f_post_ibfk_1` FOREIGN KEY (`id_user`) REFERENCES `f_user` (`id_user`);
How I can make the query to retrieve the most recent post, but considering the last comments?
This gives me the latest comments
select id_post,id_user,contenido,fecha from f_comentario group by id_post order by fecha DESC
And with that the last post,
select id_post,id_user,contenido,fecha from f_post order by fecha DESC
I have to join these two queries and then group them by the 10 most recent id_post (date) ...
Someone gives me a hand? Thank you, and greetings
Correct me if I am misunderstanding you but what you are looking for is the 10 latest id_post, id_user, contenido, fecha from the comment table based when it was last commented on rather than when the post itself was made?
select TOP 10 f_com.id_post, f_com.id_user, f_pos.contenido, f_com.contenido, f_com.fecha
from f_comentario f_com
inner join f_post f_pos
on f_pos.id_post = f_com.id_post
order by fecha DESC
This will give you the values stored inside the f_comentario table.
I think this is what you want.
It is a little difficult to understand what you trying to do because I can't understand the table names etc.
I hope this helps
p.s. Again you can use similar joins to get the user name instead of the user id and the title instead if the post id...

PHPMyAdmin - InnoDB tables will not join

This is my database structure:
CREATE database mytvguide
CREATE TABLE IF NOT EXISTS `channels` (
`id` int(11) NOT NULL auto_increment,
`channel1` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
CREATE TABLE IF NOT EXISTS `episodeairings` (
`id` mediumint(255) unsigned NOT NULL auto_increment,
`programme` varchar(255) collate utf8_unicode_ci NOT NULL,
`channel` varchar(255) collate utf8_unicode_ci default NULL,
`airdate` datetime default NULL,
`displayair` datetime default NULL,
`expiration` datetime default NULL,
`epname` varchar(256) collate utf8_unicode_ci NOT NULL,
`epno` mediumint(255) unsigned NOT NULL,
`epseries` mediumint(255) unsigned NOT NULL,
`setreminder` varchar(255) collate utf8_unicode_ci default NULL,
PRIMARY KEY (`id`),
KEY `channel` (`channel`),
KEY `programme` (`programme`),
KEY `setreminder` (`setreminder`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ROW_FORMAT=DYNAMIC AUTO_INCREMENT=3 ;
INSERT INTO `episodeairings` (`id`, `programme`, `channel`, `airdate`, `displayair`, `expiration`, `epname`, `setreminder`) VALUES
(1, 'TV Programme 1', 'ITV2', '2011-07-09 22:35:00', '2011-06-30 22:35:00', '2011-06-30 23:05:00', 'Episode', '' , '', NULL),
(2, 'TV Programme 1', 'ITV2', '2011-07-10 02:25:00', '2011-07-01 02:25:00', '2011-07-01 02:55:00', 'EpisodeTest', '1', '2', NULL);
CREATE TABLE IF NOT EXISTS `episode` (
`id` int(11) NOT NULL auto_increment,
`epname` varchar(255) NOT NULL,
`seriesnumber` int(11) NOT NULL,
`episodenumber` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `epname` (`epname`),
KEY `seriesnumber` (`seriesnumber`),
KEY `episodenumber` (`episodenumber`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
INSERT INTO `episode` (`id`, `epname`, `seriesnumber`, `episodenumber`) VALUES
(1, 'Episode', 1, 1);
CREATE TABLE IF NOT EXISTS `programme1` (
`id` int(11) NOT NULL auto_increment,
`programme` varchar(255) NOT NULL default 'Police, Camera, Action!',
PRIMARY KEY (`id`),
KEY `programme` (`programme`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
INSERT INTO `programme1` (`id`, `programme`) VALUES
(1, 'TV Programme 1');
INSERT INTO `channels` (`id`, `channel`) VALUES
(1, 'ITV2');
For some reason I can't link any of the tables in episodeairings - namely programme, channel, airdate, epname, epno, epseries with those in the other tables
(which are programme, epname, seriesnumber, episodenumber).
Basically, the dropdown won't happen at all for linked tables, as it should do.
This is despite the fact my database is stored as InnoDB via PHPmyadmin and I set the linked tables.
Why is this and how can I fix it?
I am not sure how phpmyadmin works but I would assume that it requires you to define some foreign key constraints between your tables (e.g. using the alter table statement).
See alter table docs: http://dev.mysql.com/doc/refman/5.1/en/alter-table.html