Get 10 latest post - mysql

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...

Related

how can I get a field value in 3 association tables with the max of date

So, I have a table and I want to get the value from one field in the record with the greatest DateTime() value in another field and where still another field is equal to a certain value.
--
-- Structure de la table `site`
--
CREATE TABLE IF NOT EXISTS `site` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`site_name` varchar(15) NOT NULL,
`city` varchar(50) DEFAULT NULL,
`address` varchar(80) DEFAULT NULL,
`entity` varchar(50) DEFAULT NULL,
`status_activity` tinyint(1) NOT NULL DEFAULT '1',
`infra` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
KEY `idx_site_name` (`site_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;
--
-- Contenu de la table `site`
--
INSERT INTO `site` (`id`, `site_name`, `city`, `address`, `entity`, `status_activity`, `infra`) VALUES
(1, 'FR001', 'tttt', 'tttttttttt', 'yyyyy', 1, 0),
(2, 'FR002', 'ccccc', 'cccccccccc', 'rrrrrrrrrrrr', 1, 0);
-- --------------------------------------------------------
--
-- Structure de la table `site_topology`
--
CREATE TABLE IF NOT EXISTS `site_topology` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`id_site` int(10) unsigned NOT NULL,
`id_topology` int(10) unsigned NOT NULL,
`date` date NOT NULL,
PRIMARY KEY (`id`),
KEY `idx_site_date` (`date`),
KEY `fk_id_site_2` (`id_site`),
KEY `fk_id_topology_2` (`id_topology`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=7 ;
--
-- Contenu de la table `site_topology`
--
INSERT INTO `site_topology` (`id`, `id_site`, `id_topology`, `date`) VALUES
(1, 1, 1, '2015-03-03'),
(2, 2, 3, '2015-03-03'),
(3, 1, 2, '2015-04-30'),
(4, 2, 5, '2015-04-30'),
(5, 1, 1, '2015-06-25'),
(6, 2, 4, '2015-06-25');
-- --------------------------------------------------------
--
-- Structure de la table `topology`
--
CREATE TABLE IF NOT EXISTS `topology` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(10) NOT NULL,
PRIMARY KEY (`id`),
KEY `idx_type_name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=7 ;
--
-- Contenu de la table `topology`
--
INSERT INTO `topology` (`id`, `name`) VALUES
(3, 'C1/C2'),
(2, 'C3'),
(5, 'HBN'),
(4, 'Infrastruc'),
(6, 'LB'),
(1, 'SHBN');
--
-- Contraintes pour les tables exportées
--
--
-- Contraintes pour la table `site_topology`
--
ALTER TABLE `site_topology`
ADD CONSTRAINT `fk_id_site_2` FOREIGN KEY (`id_site`) REFERENCES `site` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `fk_id_topology_2` FOREIGN KEY (`id_topology`) REFERENCES `topology` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
I want to see
FR001 SHBN 2015-06-26
FR002 Infrastruct 2015-06-26
but when I execute my query I have this
FR001 SHBN 2015-06-26`enter code here`
FR002 C1/C2 2015-06-26
Can anyone help me?
You had a problem on how to choose the max date, since the month was showing first. A different way is to bring up the max_date value (from a sub-query). After it you can compare by the different parts of the date. Code as follows:
select site_name, site_date, name
from
(
select site_name, st.date as site_date, name, s.id, (select max(sto.date) from site_topology sto) as max_date
from site s
inner join site_topology st on s.id =st.id_site
inner join topology t on st.id_topology = t.id
) as v
where YEAR(site_date) = YEAR(max_date) AND MONTH(site_date) = MONTH(max_date) AND DAY(site_date) = DAY(max_date)
group by name
order by site_name
Testing here.
use a subquery they're correct's aggregate Results here
select site_name,max(date), name
from
(select site_name,
city, address, entity , status_activity, infra,
st.*,name
from site s
inner join site_topology st on s.id =st.id_site
inner join topology t on st.id_topology = t.id )
as v
group by site_name

#1451 - Cannot delete or update a parent row: a foreign key constraint fails

My code SQL is :
enter code here
CREATE TABLE IF NOT EXISTS `participer` (
`statut_Invitation` tinyint(1) NOT NULL,
`NumVersion` int(11) NOT NULL,
`InviteCode` varchar(255) NOT NULL,
`IdQuest` int(11) NOT NULL,
PRIMARY KEY (`NumVersion`,`InviteCode`,`IdQuest`),
KEY `FK_Participer_NumVersion` (`NumVersion`),
KEY `FK_Participer_IdQuest` (`IdQuest`),
KEY `FK_Participer_InviteCode` (`InviteCode`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `participer` (`statut_Invitation`, `NumVersion`, `InviteCode`, `IdQuest`) VALUES
(0, 2, '2548', 1),
(0, 2, '8742', 1);
CREATE TABLE IF NOT EXISTS `questionnaire` (
`IdQuest` int(11) NOT NULL AUTO_INCREMENT,
`Nom` varchar(256) DEFAULT NULL,
`DateCreation` date DEFAULT NULL
PRIMARY KEY (`IdQuest`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;
INSERT INTO `questionnaire` (`IdQuest`, `Nom`, `DateCreation`, `ID`) VALUES
(1, 'Parions Sport', '2015-03-23'),
(2, 'GPS', '2015-03-23');
CREATE TABLE IF NOT EXISTS `utilisateurs` (
`InviteCode` varchar(255) NOT NULL,
`Email` varchar(25) NOT NULL,
`DateNaissance` date DEFAULT NULL,
`Ville` varchar(25) DEFAULT NULL,
PRIMARY KEY (`InviteCode`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `utilisateurs` (`InviteCode`, `Email`, `DateNaissance`, `Ville`) VALUES
('1235314', 'bocchi#gmail.com', NULL, NULL),
('2548', 'bocchiTEST#gmail.com', NULL, NULL),
('337752493652424404824466004444846460026', 'dylan#gmail.com', NULL, NULL),
('53131172170670664482420846024208824402', 'dylan2#gmail.com', NULL, NULL),
('5446544', 'lool', NULL, NULL),
('8742', 'max#gmail.com', NULL, NULL);
-- --------------------------------------------------------
CREATE TABLE IF NOT EXISTS `versionquestionnaire` (
`NumVersion` int(11) NOT NULL,
`DateExpiration` date DEFAULT NULL,
`SommeNote` float DEFAULT NULL,
`NbReponses` int(11) DEFAULT NULL,
`IdQuest` int(11) NOT NULL,
PRIMARY KEY (`NumVersion`,`IdQuest`),
KEY `FK_VersionQuestionnaire_IdQuest` (`IdQuest`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `versionquestionnaire` (`NumVersion`, `DateExpiration`, `SommeNote`, `NbReponses`, `IdQuest`) VALUES
(1, '2015-03-26', 120, 2, 1),
(1, '2015-03-30', 100, 1, 2),
(2, '2015-03-26', 210, 3, 1),
(2, '2015-03-30', 300, 4, 2);
ALTER TABLE `participer`
ADD CONSTRAINT `FK_Participer_IdQuest` FOREIGN KEY (`IdQuest`) REFERENCES `versionquestionnaire` (`IdQuest`),
ADD CONSTRAINT `FK_Participer_InviteCode` FOREIGN KEY (`InviteCode`) REFERENCES `utilisateurs` (`InviteCode`),
ADD CONSTRAINT `FK_Participer_NumVersion` FOREIGN KEY (`NumVersion`) REFERENCES `versionquestionnaire` (`NumVersion`);
ALTER TABLE `versionquestionnaire`
ADD CONSTRAINT `FK_VersionQuestionnaire_IdQuest` FOREIGN KEY (`IdQuest`) REFERENCES `questionnaire` (`IdQuest`);
When i want to delete the version 1 of the questionnaire 1 :
DELETE FROM `versionquestionnaire` WHERE `versionquestionnaire`.`NumVersion` = 1 AND `versionquestionnaire`.`IdQuest` = 1;
I have a error :
1451 - Cannot delete or update a parent row: a foreign key constraint fails (`testbug`.`participer`, CONSTRAINT `FK_Participer_IdQuest` FOREIGN KEY (`IdQuest`) REFERENCES `versionquestionnaire` (`IdQuest`)) ;
I don't understand because in the table participer, there isn't the couple with NumVersion = 1 and IdQuest = 1, there are 2 couples with NumVersion = 1 and IdQuest = 1. So my request may be run.
In short, you can't delete records from versionquestionnaire because some records in participer table reference records in participer.
Your request clearly violates IdQuest constraint: you're trying to delete a record with IdQuest = 1, while BOTH participants that still reference that ID.

MySQL joining 2 tables in to one main table

I have 2 tables 'cat' and 'sub_cat' and these two tables should join or something with main table 'product'
I tried all joining methods and non of them gave me right result I want.
I'm sure there is a method. I don't know what to call.
Sample SQL
This is how the last query should be
forget about the normalization theories and every thing and I just want the last query to be like this or mysql method that I can use on this.
cat_id cannot be duplicate
s_id should also cannot be duplicate
like in third row there can be: cat_id but no s_id the s_id should be null
if there is no cat_id and no s_id both should be null like fourth row
p_id can be duplicate
can't use group by or distinct cause it doesn't give null values then as i know
only method i got closer is using left joining both cat and sub_cat to prod table but it gives me duplicate cat_id and s_id and can't use group by or distinct on this cause there should be null values.
here is the test data
CREATE TABLE IF NOT EXISTS `cat` (
`product_id` int(11) DEFAULT NULL,
`cat_id` int(11) DEFAULT NULL,
`cat_name` varchar(10) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO `cat` (`product_id`, `cat_id`, `cat_name`) VALUES
(1, 1, 'cat1'),
(2, 2, 'cat2'),
(3, 3, 'cat3'),
(1, 4, 'ca4');
CREATE TABLE IF NOT EXISTS `prod` (
`product_id` int(11) DEFAULT NULL,
`name` varchar(10) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO `prod` (`product_id`, `name`) VALUES
(1, 'prod1'),
(2, 'prod2'),
(3, 'pro3'),
(4, 'prod4');
CREATE TABLE IF NOT EXISTS `sub_cat` (
`product_id` int(11) DEFAULT NULL,
`sub_cat_id` int(11) DEFAULT NULL,
`sub_cat_name` varchar(10) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO `sub_cat` (`product_id`, `sub_cat_id`, `sub_cat_name`) VALUES
(1, 1, 'sub cat 1'),
(2, 2, 'sub cat 2'),
(1, 3, 'sub3');
I have done a similar thing in this one.prop_cat acts as you Category table,prop_subcat as your subcategory table and property as you product.
CREATE TABLE `prop_cat` (
`pcat_id` int(11) NOT NULL AUTO_INCREMENT,
`pcat_name` varchar(60) DEFAULT NULL,
PRIMARY KEY (`pcat_id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
CREATE TABLE `prop_subcat` (
`psubcat_id` int(11) NOT NULL,
`pcat_id` int(11) NOT NULL,
`psubcat_name` varchar(45) DEFAULT NULL,
PRIMARY KEY (`psubcat_id`,`pcat_id`),
KEY `pspc_idx` (`pcat_id`),
CONSTRAINT `catsub` FOREIGN KEY (`pcat_id`) REFERENCES `prop_cat` (`pcat_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `property` (
`prop_id` int(11) NOT NULL AUTO_INCREMENT,
`prop_name` varchar(25) DEFAULT NULL,
`price` double DEFAULT NULL,
`location` varchar(50) DEFAULT NULL,
`image` varchar(60) DEFAULT NULL,
`area` double DEFAULT NULL,
`psubcat_id` int(11) DEFAULT NULL,
`description` text,
PRIMARY KEY (`prop_id`),
KEY `psub_idx` (`psubcat_id`),
CONSTRAINT `psub` FOREIGN KEY (`psubcat_id`) REFERENCES `prop_subcat` (`pcat_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
SELECT
prop_cat.`pcat_id` AS prop_cat_pcat_id,
prop_cat.`pcat_name` AS prop_cat_pcat_name,
prop_subcat.`psubcat_id` AS prop_subcat_psubcat_id,
prop_subcat.`pcat_id` AS prop_subcat_pcat_id,
prop_subcat.`psubcat_name` AS prop_subcat_psubcat_name,
property.`prop_id` AS property_prop_id,
property.`prop_name` AS property_prop_name,
property.`price` AS property_price,
property.`location` AS property_location,
property.`image` AS property_image,
property.`area` AS property_area,
property.`psubcat_id` AS property_psubcat_id,
property.`description` AS property_description
FROM
`prop_cat` prop_cat INNER JOIN `prop_subcat` prop_subcat ON prop_cat.`pcat_id` = prop_subcat.`pcat_id`
INNER JOIN `property` property ON prop_subcat.`pcat_id` = property.`psubcat_id`

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 ;

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