Retail inventory system Mysql query optimization - php

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?

Related

Unable to create foreign key in PHPmyadmin

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

Yii2-Integrity constraint violation – yii\db\IntegrityException

Integrity constraint violation – yii\db\IntegrityException
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`jts`.`employee`, CONSTRAINT `employee_ibfk_1` FOREIGN KEY (`client_code`) REFERENCES `client` (`client_code`))
The SQL being executed was: INSERT INTO `employee` (`client_code`, `company_name`, `emp_email`, `emp_mobile`, `emp_first_name`, `emp_last_name`) VALUES ('12345678', 'PVPPCOE', 'saurabhkulkarni2010#hotmail.com', '+449029792183', 'Saurabh', 'Kulkarni')
Error Info: Array
(
[0] => 23000
[1] => 1452
[2] => Cannot add or update a child row: a foreign key constraint fails (`jts`.`employee`, CONSTRAINT `employee_ibfk_1` FOREIGN KEY (`client_code`) REFERENCES `client` (`client_code`))
)
I have three tables Client, Employee and create_client, out of which client and employee has two foreign keys.
This problem is showing when I try to insert data from create_client to employee which has exact same field.
What should I do so that I can insert two tables at one i.e create_client and employee
UPDATE-
Table Structure
1)client
CREATE TABLE IF NOT EXISTS `client` (
`id` int(11) NOT NULL,
`client_code` varchar(11) NOT NULL,
`company_name` varchar(45) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=29 DEFAULT CHARSET=utf8;
2)create_client
CREATE TABLE IF NOT EXISTS `create_client` (
`id` int(11) NOT NULL,
`client_code` varchar(11) NOT NULL,
`company_name` varchar(45) NOT NULL,
`emp_email` varchar(45) NOT NULL,
`emp_mobile` varchar(45) NOT NULL,
`emp_first_name` varchar(45) NOT NULL,
`emp_last_name` varchar(45) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=43 DEFAULT CHARSET=utf8;
3)employee
CREATE TABLE IF NOT EXISTS `employee` (
`id` int(11) NOT NULL,
`client_code` varchar(11) NOT NULL,
`company_name` varchar(45) NOT NULL,
`emp_email` varchar(45) NOT NULL,
`emp_mobile` varchar(45) NOT NULL,
`emp_first_name` varchar(45) NOT NULL,
`emp_last_name` varchar(45) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8;
This is my table structure, first user will create client that means first it will update create_client. Now if user wants he can add many employee under one client code now user will update employee table from Yii2 dynamic form widget.
For using this widget I have created one table call client this will store only client_code and company name remaining data will go in employee table e.g emp_mobile,emp_email, emp_first_name, emp_last_name.
Now this problem is pop up when user first enters data into create_client table.
everything is working between client and employee table user able to enter as many employee as it wants using Yii2 dynamic form Widget but not working for create_client
Apparently you also have a foreign key in the employee table referencing the client_code of the client table, so you can only use client_code values that already exist in the client table.
I don't know what the structure of the create_client table looks like and what its purpose is, but based on your info I assume that you should first insert the data in client, then in employee and finally in create_client, so that every foreign key's value exists in its respective table.
If this is not correct, please post your table structures and the data or queries that could be causing this.
Edit after your comment: I assume that your table structure looks like this:
CREATE TABLE `create_client` (
`client_code` INT UNSIGNED NOT NULL,
`company_name` VARCHAR(255) NOT NULL,
`emp_mobile` VARCHAR(255) NOT NULL,
`emp_email` VARCHAR(255) NOT NULL,
`emp_first_name` VARCHAR(255) NOT NULL,
`emp_last_name` VARCHAR(255) NOT NULL,
UNIQUE KEY `client_code` (`client_code`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
CREATE TABLE `client` (
`client_code` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`company_name` VARCHAR(255) NOT NULL,
PRIMARY KEY `client_code` (`client_code`),
CONSTRAINT `client_ibfk_1` FOREIGN KEY (`client_code`) REFERENCES `create_client` (`client_code`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
CREATE TABLE `employee` (
`client_code` INT UNSIGNED NOT NULL,
`company_name` VARCHAR(255) NOT NULL,
`emp_mobile` VARCHAR(255) NOT NULL,
`emp_email` VARCHAR(255) NOT NULL,
`emp_first_name` VARCHAR(255) NOT NULL,
`emp_last_name` VARCHAR(255) NOT NULL,
KEY `client_code` (`client_code`),
CONSTRAINT `employee_ibfk_1` FOREIGN KEY (`client_code`) REFERENCES `client` (`client_code`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
However, I would suggest to use client as the parent table and move the foreign key constraint to create_client, so that both employee and create_client have a foreign key of client. I would also like to normalise this and get rid of company_name in the child tables:
CREATE TABLE `client` (
`client_code` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`company_name` VARCHAR(255) NOT NULL,
PRIMARY KEY `client_code` (`client_code`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
CREATE TABLE `create_client` (
`client_code` INT UNSIGNED NOT NULL,
`emp_mobile` VARCHAR(255) NOT NULL,
`emp_email` VARCHAR(255) NOT NULL,
`emp_first_name` VARCHAR(255) NOT NULL,
`emp_last_name` VARCHAR(255) NOT NULL,
UNIQUE KEY `client_code` (`client_code`),
CONSTRAINT `create_client_ibfk_1` FOREIGN KEY (`client_code`) REFERENCES `client` (`client_code`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
CREATE TABLE `employee` (
`client_code` INT UNSIGNED NOT NULL,
`emp_mobile` VARCHAR(255) NOT NULL,
`emp_email` VARCHAR(255) NOT NULL,
`emp_first_name` VARCHAR(255) NOT NULL,
`emp_last_name` VARCHAR(255) NOT NULL,
KEY `client_code` (`client_code`),
CONSTRAINT `employee_ibfk_1` FOREIGN KEY (`client_code`) REFERENCES `client` (`client_code`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
The next improvement would be to use the employee table for both unique and non-unique client_code inserts. Instead of using 2 identical tables, apart from the unique key, you could do the unique validation in Yii instead of in MySQL. You can specify the table name in the tableName() method of the CreateClient model . This will remain:
CREATE TABLE `client` (
`client_code` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`company_name` VARCHAR(255) NOT NULL,
PRIMARY KEY `client_code` (`client_code`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
CREATE TABLE `employee` (
`client_code` INT UNSIGNED NOT NULL,
`emp_mobile` VARCHAR(255) NOT NULL,
`emp_email` VARCHAR(255) NOT NULL,
`emp_first_name` VARCHAR(255) NOT NULL,
`emp_last_name` VARCHAR(255) NOT NULL,
KEY `client_code` (`client_code`),
CONSTRAINT `employee_ibfk_1` FOREIGN KEY (`client_code`) REFERENCES `client` (`client_code`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
This should allow you to use the dynamic form, with Client as the main model and Employee as the items model.
On Yii2 using IO Generator (Model) and MySQL I have found the following.
I have seen SET '' instead of SET NULL in update SQL statement(s) on field(s) with foreign key constraints that have caused a "Integrity constraint violation".
My "fix" is to add a default rule on the foreign key field in the model, like so:
public function rules()
{
return [
//
// your other rules
//
[['field_name_with_foreign_key'], 'default', 'value' => null],
];
}
Hope this helps someone.
remove all foreign key checks and simplify database.
the problem lies in your foreign key structure.
learn carefully about primary keys and foreign keys.
make new database again without foreign keys then check.

MYSQL multiple join error and learning

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.

#1005 - Can't create table 'database.viewers' (errno: -1)

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

Troubled with making a PHP db driven multiple choice Quiz

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!');

Categories