I appreciate your patience as I am still trying to learn joining tables. I have in the past done joins between two tables, and I would nest them in the php code which I am sure is incorrect and very inefficient. I would like to learn the "right" way.
Here is my query so far. I am getting an error: unknown column in on clause
SELECT PermissionID FROM Permissions
INNER JOIN PermissionsAssigned ON Permissions.PermissionID = PermissionsAssigned.PermissionID
INNER JOIN Roles ON PermissionsAssigned.RoleID = Roles.RoleID
INNER JOIN RolesAssigned ON Roles.RoleID = RolesAssigned.RoleID
INNER JOIN UserDirectory ON RolesAssigned.UserID = UserDirectory.UserID
WHERE UserDirectory.UserID = 4
CREATE TABLE IF NOT EXISTS `Permissions` (
`PermissionID` int(11) NOT NULL AUTO_INCREMENT,
`Description` tinytext NOT NULL,
PRIMARY KEY (`PermissionID`),
UNIQUE KEY `ID_UNIQUE` (`PermissionID`),
KEY `Index 1` (`PermissionID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `PermissionsAssigned` (
`PermissionsAssignedID` int(11) NOT NULL AUTO_INCREMENT,
`Permission ID` int(11) NOT NULL DEFAULT '0',
`RoleID` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`PermissionsAssignedID`),
UNIQUE KEY `PermissionsAssignedID_UNIQUE` (`PermissionsAssignedID`),
KEY `FK_PermissionsAssigned_Permissions` (`Permission ID`),
KEY `FK_PermissionsAssigned_Roles` (`RoleID`),
KEY `Index 1` (`PermissionsAssignedID`),
CONSTRAINT `FK_PermissionsAssigned_Permissions` FOREIGN KEY (`Permission ID`) REFERENCES `Permissions` (`PermissionID`),
CONSTRAINT `FK_PermissionsAssigned_Roles` FOREIGN KEY (`RoleID`) REFERENCES `Roles` (`RoleID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `Roles` (
`RoleID` int(11) NOT NULL AUTO_INCREMENT,
`Description` tinytext NOT NULL,
PRIMARY KEY (`RoleID`),
UNIQUE KEY `ID_UNIQUE` (`RoleID`),
KEY `Index 1` (`RoleID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `RolesAssigned` (
`RoleAssignedID` int(11) NOT NULL AUTO_INCREMENT,
`UserID` int(11) NOT NULL,
`RoleID` int(11) NOT NULL,
PRIMARY KEY (`RoleAssignedID`),
UNIQUE KEY `ID_UNIQUE` (`RoleAssignedID`),
KEY `Index 1` (`RoleAssignedID`),
KEY `FK_RolesAssigned_UserDirectory` (`UserID`),
KEY `FK_RolesAssigned_Roles` (`RoleID`),
CONSTRAINT `FK_RolesAssigned_Roles` FOREIGN KEY (`RoleID`) REFERENCES `Roles` (`RoleID`),
CONSTRAINT `FK_RolesAssigned_UserDirectory` FOREIGN KEY (`UserID`) REFERENCES `UserDirectory` (`UserID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `UserDirectory` (
`UserID` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`UserID`),
UNIQUE KEY `UserID_UNIQUE` (`UserID`),
KEY `Index 1` (`UserID`),
KEY `FK_UserDirectory_Departments` (`DepartmentID`),
CONSTRAINT `FK_UserDirectory_Departments` FOREIGN KEY (`DepartmentID`) REFERENCES `Departments` (`DepartmentID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Thanks!
Matthew
CREATE TABLE IF NOT EXISTS `PermissionsAssigned` (
`PermissionsAssignedID` int(11) NOT NULL AUTO_INCREMENT,
***`Permission ID`*** int(11) NOT NULL DEFAULT '0',
HERE is the problem
change Permission ID to PermissionID in you database
You need to make table definition proper like
CREATE TABLE IF NOT EXISTS `PermissionsAssigned` (
`PermissionsAssignedID` int(11) NOT NULL AUTO_INCREMENT,
`PermissionID` int(11) NOT NULL DEFAULT '0'`, .................
PermissionID should be a Whole word . Check in your Code its having space.
Related
I am trying to create foreign key in one of my table but i am getting this error can you help with this
CREATE TABLE IF NOT EXISTS `albums` (
`id` smallint(5) unsigned NOT NULL,
`url` mediumtext NOT NULL,
`year` mediumint(9) NOT NULL,
`album_name` varchar(150) NOT NULL,
`album_cover` text NOT NULL,
`tracks_id` text NOT NULL,
`category` tinyint(4) NOT NULL,
`reciter` tinyint(4) NOT NULL,
`keywords` varchar(300) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
Foreign Key Table Structure
CREATE TABLE IF NOT EXISTS `album_likes` (
`album_id` int(5) NOT NULL,
`likes` int(11) NOT NULL,
`dislikes` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Now what i did to make this foreign key is that i went to the structure of this table in phpmyadmin and then add constraint name select the columns
Here is the query
ALTER TABLE `album_likes` ADD CONSTRAINT `album_like_fk` FOREIGN KEY (`album_id`) REFERENCES `mp3script`.`albums`(`id`) ON DELETE CASCADE ON UPDATE NO ACTION;
The output i got
1215 - Cannot add foreign key constraint
A foreign key requires an index on the column you are referencing, in this case albums.id.
Add the index:
CREATE INDEX ids_nn_1 on albums(id);
And you create foreign key should work
I'm looking to optimize the following Mysql query that is used to calculate the cost of inventory for a number of stores, I'm running the following query through a PHP loop for each distinct store and outputting the result:
Query:
SELECT
SUM((((
(SELECT COALESCE(SUM(facturas_fabrica.cantidad), 0)
FROM facturas_fabrica
INNER JOIN entradas_pedidos_productos ON
entradas_pedidos_productos.clave = facturas_fabrica.entradas_pedidos_productos_clave
INNER JOIN entradas_pedidos ON entradas_pedidos.clave = entradas_pedidos_productos.entradas_pedidos_clave
WHERE entradas_pedidos_productos.producto_id = productos.id
AND facturas_fabrica.procesado_local = 1 AND entradas_pedidos.sucursal_id = '.$row['id'].' # store id
AND DATE(facturas_fabrica.fecha_procesada) <= DATE(NOW()))
-
(SELECT COALESCE(SUM(cantidad), 0)
FROM facturas_contenido
WHERE producto_id = productos.id AND facturas_contenido.sucursal_id = '.$row['id'].'
AND DATE(facturas_contenido.fecha_creacion) <= DATE(NOW()))
+
(SELECT COALESCE(SUM(cantidad), 0)
FROM notas_de_credito_contenido
WHERE producto_id = productos.id AND notas_de_credito_contenido.sucursal_id = '.$row['id'].'
AND DATE(notas_de_credito_contenido.fecha_creacion) <= DATE(NOW()))
-
(SELECT COALESCE(SUM(salidas_devoluciones.cantidad), 0)
FROM salidas_devoluciones
WHERE producto_id = productos.id AND (estado = 2 OR estado = 3) AND modulo != 2 AND salidas_devoluciones.sucursal_id = '.$row['id'].' # store id
AND DATE(salidas_devoluciones.fecha_envio) <= DATE(NOW()))
) * productos.costo) / 100) ) AS "'.$row['clave'].'" # store name
FROM productos WHERE 1
(I'm only keeping fields relevant to the query)
Table 1:
CREATE TABLE `productos` (
`id` int(10) unsigned NOT NULL,
`costo` int(10) NOT NULL,
PRIMARY KEY (`id`),
KEY `costo` (`costo`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Table 2:
CREATE TABLE `facturas_fabrica` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`clave` bigint(20) unsigned NOT NULL,
`entradas_pedidos_productos_clave` bigint(20) unsigned NOT NULL,
`cantidad` tinyint(3) unsigned NOT NULL,
`procesado_local` tinyint(1) NOT NULL DEFAULT '0',
`fecha_procesada` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `clave_UNIQUE` (`clave`),
KEY `fk_entradas_pedidos_productos_clave_idx` (`entradas_pedidos_productos_clave`),
KEY `facturas_fabrica_procesado_local` (`procesado_local`),
KEY `facturas_fabrica_cantidad` (`cantidad`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Constraints for table `facturas_fabrica`
--
ALTER TABLE `facturas_fabrica`
ADD CONSTRAINT `fk_entradas_pedidos_productos_clave` FOREIGN KEY (`entradas_pedidos_productos_clave`) REFERENCES `entradas_pedidos_productos` (`clave`) ON DELETE NO ACTION ON UPDATE NO ACTION;
Table 3:
CREATE TABLE `entradas_pedidos_productos` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`clave` bigint(20) unsigned NOT NULL,
`entradas_pedidos_clave` bigint(20) unsigned NOT NULL,
`producto_id` int(10) unsigned NOT NULL,
`cantidad` tinyint(3) unsigned NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `clave_UNIQUE` (`clave`),
KEY `fk_pedidos_producto_id_idx` (`producto_id`),
KEY `fk_pedidos_productos_pedido_clave_idx` (`entradas_pedidos_clave`),
KEY `entradas_productos_cantidad` (`cantidad`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Constraints for table `entradas_pedidos_productos`
--
ALTER TABLE `entradas_pedidos_productos`
ADD CONSTRAINT `fk_pedidos_productos_pedido_clave` FOREIGN KEY (`entradas_pedidos_clave`) REFERENCES `entradas_pedidos` (`clave`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `fk_pedidos_productos_producto_id` FOREIGN KEY (`producto_id`) REFERENCES `productos` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
Table 4:
CREATE TABLE `entradas_pedidos` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`clave` bigint(20) unsigned NOT NULL,
`sucursal_id` tinyint(3) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `clave_UNIQUE` (`clave`),
KEY `clave` (`clave`),
KEY `entradas_sucursal` (`sucursal_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Constraints for table `entradas_pedidos`
--
ALTER TABLE `entradas_pedidos`
ADD CONSTRAINT `fk_entradas_pedidos_sucursal_is` FOREIGN KEY (`sucursal_id`) REFERENCES `sucursales` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
Table 5:
CREATE TABLE `facturas_contenido` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`clave` bigint(20) unsigned NOT NULL,
`sucursal_id` tinyint(3) NOT NULL,
`producto_id` int(10) unsigned NOT NULL,
`cantidad` tinyint(3) unsigned NOT NULL,
`fecha_creacion` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `clave_factura_contenido` (`clave`),
KEY `fk_orden_contenido_producto_id_idx` (`producto_id`),
KEY `facturas_contenido_cantidad` (`cantidad`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Constraints for table `facturas_contenido`
--
ALTER TABLE `facturas_contenido`
ADD CONSTRAINT `fk_facturas_clave` FOREIGN KEY (`factura_clave`) REFERENCES `facturas` (`clave`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `fk_facturas_contenido_producto_id` FOREIGN KEY (`producto_id`) REFERENCES `productos` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
Table 6:
CREATE TABLE `notas_de_credito_contenido` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`clave` bigint(20) unsigned NOT NULL,
`sucursal_id` tinyint(3) NOT NULL,
`producto_id` int(10) unsigned NOT NULL,
`cantidad` tinyint(3) unsigned NOT NULL,
`fecha_creacion` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `clave_nota_de_credito_contenido` (`clave`),
KEY `fk_nc_clave_idx` (`nc_clave`),
KEY `fk_ordenes_contenido_clave_idx` (`nc_facturas_contenido_clave`),
KEY `notas_de_credito_cantidad` (`cantidad`),
KEY `notas_de_credito_producto_id` (`producto_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Constraints for dumped tables
--
--
-- Constraints for table `notas_de_credito_contenido`
--
ALTER TABLE `notas_de_credito_contenido`
ADD CONSTRAINT `fk_facturas_contenido_clave` FOREIGN KEY (`nc_facturas_contenido_clave`) REFERENCES `facturas_contenido` (`clave`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `fk_nc_clave` FOREIGN KEY (`nc_clave`) REFERENCES `notas_de_credito` (`clave`) ON DELETE NO ACTION ON UPDATE NO ACTION;
Table 7:
CREATE TABLE `salidas_devoluciones` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`clave` bigint(20) unsigned NOT NULL,
`producto_id` int(10) unsigned NOT NULL,
`cantidad` tinyint(3) unsigned NOT NULL,
`sucursal_id` tinyint(3) NOT NULL,
`fecha_envio` timestamp NULL DEFAULT NULL,
`estado` tinyint(3) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
UNIQUE KEY `clave_UNIQUE` (`clave`),
KEY `salidas_devoluciones_cantidad` (`cantidad`),
KEY `fk_salidas_producto_id_idx` (`producto_id`),
KEY `devoluciones_estado` (`estado`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Constraints for table `salidas_devoluciones`
--
ALTER TABLE `salidas_devoluciones`
ADD CONSTRAINT `fk_salidas_producto_id` FOREIGN KEY (`producto_id`) REFERENCES `productos` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
The problem is because of the large amount of stores and movements in each store the query is becoming increasingly heavy, and because inventory is calculated from the beginning of each store's history it only gets slower with time.
What could I do to optimize this scheme?
users table:
CREATE TABLE `users` (
`uid` int(11) NOT NULL AUTO_INCREMENT,
`unique_id` varchar(23) NOT NULL,
`full_name` varchar(100) DEFAULT NULL,
`name` varchar(50) NOT NULL,
`email` varchar(100) NOT NULL,
PRIMARY KEY (`uid`),
UNIQUE KEY `unique_id` (`unique_id`) USING BTREE,
UNIQUE KEY `email` (`email`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=41 DEFAULT CHARSET=utf8;
items table:
CREATE TABLE `items` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`item_photo` text,
`item_name` varchar(100) DEFAULT NULL,
`item_description` varchar(500) DEFAULT NULL,
`item_price` varchar(10) DEFAULT NULL,
`user_id` int(11) DEFAULT NULL,
`category_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fk_user_id` (`user_id`) USING BTREE,
KEY `fk_category_id` (`category_id`) USING BTREE,
CONSTRAINT `items_ibfk_1` FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`),
CONSTRAINT `items_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `users` (`uid`)
) ENGINE=InnoDB AUTO_INCREMENT=64 DEFAULT CHARSET=utf8;
What I would wanna do is to create a private messaging system for my project. Before this I have implemented a Comment system and it works well (pull out comments which has the same item_id). You can see the DDL and query here. But when it come to this, I find it hard to think about private messaging model.
Basically, the private message is to bid the item price between TWO users only (the seller and the bidder). Other registered user cannot see others bidding.
Here's my try at creating Bids table:
CREATE TABLE `bids` (
`id` int(11) NOT NULL,
`bid` float DEFAULT NULL,
`message` varchar(255) DEFAULT NULL,
`from_uid` varchar(255) DEFAULT NULL,
`to_uid` varchar(255) DEFAULT NULL,
`to_iid` int(11) DEFAULT NULL,
`time` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
I have also tried to make Foreign Keys into bids table, but it seems like it's already too complicated for me. So an error 1215 - Cannot add foreign key constraint came out :(
If anything just let me know.
EDIT: charset to utf8. Failed to create Foreign key constraints
MESSAGES
message_id
conversation_id
user_id
message
CONVERSATIONS
conversation_id
item_id
user_id
BIDS
bid_id
item_id
user_id
amount
this table is already work fine
create table posts (
id bigint(20) unsigned not null auto_increment,
title varchar(200) not null,
content text,
mdesc varchar(340),
pdate timestamp not null default current_timestamp,
lupdate timestamp not null default '0000-00-00 00:00:00',
perma varchar(120) not null,
cat_id smallint(5) unsigned not null,
user_id int(11) unsigned not null,
views int(11) unsigned not null default 0,
status tinyint(1) unsigned not null default 0,
primary key (id),
unique key (title,cat_id),
foreign key (cat_id) references category (id) on delete restrict on update cascade,
foreign key (user_id) references users (id) on delete cascade on update cascade
) engine=innodb default charset=utf8;
but i dont know why i cant query viewers table i dont know why
create table viewers (
id int(11) unsigned not null auto_increment,
post_id bigint(20) unsigned not null,
primary key (id),
foreign key (post_id) references posts (id) on delete cascade
) engine=innodb default charset=utf8;
please help :)
Please try removing fks
Most commonly it is because of different properties.
Check
if id of post table is having same properties as of this? (here bigint)
Other possibilities could be
it isn't innodb engine for other table.
Names of fks are not unique
So my objective sounds simple, I need to make a db driven multiple choice quiz
CMS to add into my project. I need to be able to create quizzes by category, add 10 questions per quiz, and 4 questions with 1 answer. I've been troubled in 2 areas.
Database structure. How can I structure my database so that I can do this? eg, a table for each questions, question_answers, and quizzes?
After the users takes the quiz, I want to grab the score and store it into its own table. I know how to put the score into the database, but how would I display the quiz, with the corresponding question, with the corresponding answers, and the correct answer with the right radio button?
It's very tricky to me, but maybe not to some of you geniuses out there.
Best regards,
Sean
Clicked this table structure for you. The foreign key constraints are optional.
CREATE TABLE IF NOT EXISTS `answer` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`question_id` int(10) unsigned NOT NULL,
`answer` varchar(100) NOT NULL,
PRIMARY KEY (`id`),
KEY `question_id` (`question_id`)
) ENGINE=InnoDB ;
CREATE TABLE IF NOT EXISTS `question` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`quiz_id` int(10) unsigned NOT NULL,
`question` varchar(500) NOT NULL,
`correct_anwer_id` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `quiz_id` (`quiz_id`,`correct_anwer_id`),
KEY `correct_anwer_id` (`correct_anwer_id`)
) ENGINE=InnoDB ;
CREATE TABLE IF NOT EXISTS `quiz` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`category` int(10) unsigned NOT NULL,
`title` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB ;
ALTER TABLE `answer`
ADD CONSTRAINT `answer_ibfk_1` FOREIGN KEY (`question_id`) REFERENCES `question` (`id`);
ALTER TABLE `question`
ADD CONSTRAINT `question_ibfk_2` FOREIGN KEY (`correct_anwer_id`) REFERENCES `answer` (`id`),
ADD CONSTRAINT `question_ibfk_1` FOREIGN KEY (`quiz_id`) REFERENCES `quiz` (`id`);
And for storing the test, users have taken:
CREATE TABLE IF NOT EXISTS `test` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`user_id` int(10) unsigned NOT NULL,
`quiz_id` int(10) unsigned NOT NULL,
`date_taken` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`score` mediumint(9) NOT NULL,
PRIMARY KEY (`id`),
KEY `quiz_id` (`quiz_id`)
) ENGINE=InnoDB ;
CREATE TABLE IF NOT EXISTS `test_answer` (
`test_id` int(10) unsigned NOT NULL,
`question_id` int(10) unsigned NOT NULL,
`answer_id` int(10) unsigned NOT NULL,
`single_score` mediumint(9) NOT NULL,
PRIMARY KEY (`test_id`,`question_id`),
KEY `question_id` (`question_id`),
KEY `answer_id` (`answer_id`)
) ENGINE=InnoDB ;
ALTER TABLE `test`
ADD CONSTRAINT `test_ibfk_1` FOREIGN KEY (`quiz_id`) REFERENCES `quiz` (`id`);
ALTER TABLE `test_answer`
ADD CONSTRAINT `test_answer_ibfk_3` FOREIGN KEY (`answer_id`) REFERENCES `answer` (`id`),
ADD CONSTRAINT `test_answer_ibfk_1` FOREIGN KEY (`test_id`) REFERENCES `test` (`id`),
ADD CONSTRAINT `test_answer_ibfk_2` FOREIGN KEY (`question_id`) REFERENCES `question` (`id`);
Some sample data to play around:
INSERT INTO `answer` (`id`, `question_id`, `answer`) VALUES
(3, 1, 'stackoverflow.com '),
(4, 1, 'example.com');
INSERT INTO `question` (`id`, `quiz_id`, `question`, `correct_anwer_id`) VALUES
(6, 1, 'What is the best website on the whole internet?', 3);
INSERT INTO `quiz` (`id`, `category`, `title`) VALUES
(1, 1337, 'My Great Quiz. Take me!');