Complex SQL or Eloquent query - mysql

I have this Database schema
exercise_quiz table
CREATE TABLE `exercise_quiz` (
`exercise_id` int(10) unsigned NOT NULL,
`quiz_id` int(10) unsigned NOT NULL,
`user_id` int(10) unsigned NOT NULL,
`answer` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`exercise_id`,`quiz_id`,`user_id`),
KEY `exercise_quiz_user_id_foreign` (`user_id`),
KEY `exercise_quiz_quiz_id_foreign` (`quiz_id`),
CONSTRAINT `exercise_quiz_exercise_id_foreign` FOREIGN KEY (`exercise_id`) REFERENCES `exercises` (`id`) ON DELETE CASCADE,
CONSTRAINT `exercise_quiz_quiz_id_foreign` FOREIGN KEY (`quiz_id`) REFERENCES `quizzes` (`id`) ON DELETE CASCADE,
CONSTRAINT `exercise_quiz_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
exercises table
CREATE TABLE `exercises` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`body` text COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`course_id` int(10) unsigned NOT NULL,
`score` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `exercises_course_id_foreign` (`course_id`),
CONSTRAINT `exercises_course_id_foreign` FOREIGN KEY (`course_id`) REFERENCES `courses` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=145 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
quizzes table
CREATE TABLE `quizzes` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`question` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
Example of data in exercise_quiz
How can I retrieve this, either with raw SQL or with Eloquent, in such a way as I’d have one single row for each exercise_id with one column with the average answer for each quiz_id ? something like
exercise_id --- avg_quiz_1 ---- avg_quiz_2 ---- avg_quiz_3 ...

Related

Cannot add foreign key constraint

I have created a database "webportal". and this is my "user" table script
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
`firstName` varchar(255) DEFAULT NULL,
`lastName` varchar(255) DEFAULT NULL,
`dateRegistered` DATE DEFAULT NULL,
`skypeID` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
and this one is "catalog" table script.
DROP TABLE IF EXISTS `catalog`;
create table catalog(
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`link` VARCHAR(100) NOT NULL,
`comment` VARCHAR(100) NOT NULL,
`inserDate` DATE DEFAULT NULL,
`content` longblob NOT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `fk_catalog` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
and when I try to execute the second script in the command line, I get this error...
ERROR 1215 (HY000): Cannot add foreign key constraint.
What is wrong with this code?
It seems you are using a old version of MySQL, you can add a INDEX clause to foreign key field to fix the problem:
DROP TABLE IF EXISTS `catalog`;
create table `catalog`(
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`link` VARCHAR(100) NOT NULL,
`comment` VARCHAR(100) NOT NULL,
`inserDate` DATE DEFAULT NULL,
`content` longblob NOT NULL,
PRIMARY KEY (`id`),
INDEX (`user_id`),
CONSTRAINT `fk_catalog` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Unable to update a child row in my Database (MySQL)

Using the following SQL statement..
INSERT INTO `debates` (`id`, `unit_id`, `starter_pack_id`, `academic_id`, `title`, `date_due`, `date_created`, `date_modified`) VALUES
(1, 1, 1, 5, 'On Campus', '2016-12-25 00:00:00', now(), NULL),
(2, 1, 1, 5, 'Off Campus', '2016-12-25 00:00:00', now(), NULL);
Results in the following error being output..
#1452 - Cannot add or update a child row: a foreign key constraint fails (`my_database`.`debates`, CONSTRAINT `fk_debates_starter_pack_id` FOREIGN KEY (`starter_pack_id`) REFERENCES `debate_starter_packs` (`id`) ON DELETE CASCADE ON UPDATE CASCADE)
Why am I unable to update this table?
Please Note : Below are all the tables associated with this SQL statement. There are currently no tables contain any data in the database.
Debates:
CREATE TABLE `debates`(
`id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`unit_id` INT(11) UNSIGNED NOT NULL,
`starter_pack_id` TINYINT(3) UNSIGNED NOT NULL,
`academic_id` INT(11) UNSIGNED NOT NULL,
`title` VARCHAR(255) NOT NULL,
`date_due` DATETIME NOT NULL,
`date_created` DATETIME NOT NULL,
`date_modified` DATETIME DEFAULT NULL,
CONSTRAINT `pk_debates_id` PRIMARY KEY(`id`),
CONSTRAINT `fk_debates_starter_pack_id` FOREIGN KEY(`starter_pack_id`) REFERENCES `debate_starter_packs`(`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_debates_unit_id` FOREIGN KEY(`unit_id`) REFERENCES `units`(`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_debates_user_role_id` FOREIGN KEY(`academic_id`) REFERENCES `user_roles`(`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE = InnoDB DEFAULT CHARSET = utf8;
Units (Unit_ID Reference):
CREATE TABLE `units` (
`id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`academic_id` int(11) UNSIGNED NOT NULL,
`unit_code` varchar(6) NOT NULL,
`title` varchar(100) DEFAULT NULL,
`date_added` datetime NOT NULL,
`date_modified` datetime DEFAULT NULL,
CONSTRAINT `pk_units_id` PRIMARY KEY(`id`),
CONSTRAINT `fk_units_academic_id` FOREIGN KEY (`academic_id`) REFERENCES `user_roles` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Starter Packs (Starter_Pack_ID Reference):
CREATE TABLE `debate_starter_packs` (
`id` tinyint(3) UNSIGNED NOT NULL AUTO_INCREMENT,
`academic_id` int(11) UNSIGNED NOT NULL,
`title` varchar(100) NOT NULL,
`description` text NOT NULL,
`date_created` datetime NOT NULL,
`date_modified` datetime DEFAULT NULL,
CONSTRAINT `pk_debate_starter_packs_id` PRIMARY KEY(`id`),
CONSTRAINT `fk_debate_starter_packs_user_role_id` FOREIGN KEY (`academic_id`) REFERENCES `user_roles` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Users (Academic_ID Reference):
CREATE TABLE `users` (
`id` int(11) UNSIGNED NOT NULL,
`username` varchar(100) DEFAULT NULL,
`first_name` varchar(50) DEFAULT NULL,
`last_name` varchar(50) DEFAULT NULL,
`email` varchar(100) NOT NULL,
`password` varchar(255) NOT NULL,
`salt` varchar(255) DEFAULT NULL,
`organisation` varchar(100) DEFAULT NULL,
`phone` varchar(20) DEFAULT NULL,
`date_created` datetime NOT NULL,
`date_last_login` datetime DEFAULT NULL,
`remember_code` varchar(40) DEFAULT NULL,
`active` tinyint(1) UNSIGNED NOT NULL,
CONSTRAINT `pk_users_id` PRIMARY KEY(`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Do you have the record id='1' in the table debate_starter_packs ?
The table debates have a foreign key reference id of table debate_starter_packs.
CONSTRAINT `fk_debates_starter_pack_id` FOREIGN KEY(`starter_pack_id`) REFERENCES `debate_starter_packs`(`id`) ON DELETE CASCADE ON UPDATE CASCADE,
You should insert the record id='1' to the table debate_starter_packs first.

Foreign Keys on two different schemas mysql

I have two tables on distinct schemas
db1.invoice
CREATE TABLE IF NOT EXISTS db1.`invoice` (
`invoice_id` int(11) NOT NULL AUTO_INCREMENT,
`qsales_sale_id` int(11) DEFAULT NULL,
`invoice_id_from_dosage_id` int(11) NOT NULL,
`number` int(11) DEFAULT NULL,
`enterprise_name` varchar(100) DEFAULT NULL,
`subsidiary_name` varchar(100) DEFAULT NULL,
`subsidiary_address` varchar(200) DEFAULT NULL,
`subsidiary_phone` varchar(40) DEFAULT NULL,
`client_name` varchar(200) DEFAULT NULL,
`nit` bigint(20) DEFAULT NULL,
`was_paid` tinyint(1) DEFAULT NULL,
PRIMARY KEY (`invoice_id`),
KEY `fk_invoice_qsales_sale1_idx` (`qsales_sale_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=457 ;
bd2.qsale_sale
CREATE TABLE IF NOT EXISTS db2.qsales_sale (
`qsales_sale_id` int(11) NOT NULL AUTO_INCREMENT,
`qsales_order_type_id` int(11) NOT NULL,
`client_id` int(11) NOT NULL,
`total_cost` decimal(10,2) DEFAULT NULL,
`currency` varchar(45) DEFAULT NULL,
`created_at` datetime DEFAULT NULL,
`has_discount` tinyint(1) DEFAULT NULL,
`created_by` int(11) NOT NULL,
`is_wholesaler` tinyint(1) NOT NULL DEFAULT '0',
`payment_type` varchar(65) DEFAULT NULL,
PRIMARY KEY (`qsales_sale_id`),
KEY `fk_qsales_sale_qsales_order_type1_idx` (`qsales_order_type_id`),
KEY `fk_qsales_sale_client1_idx` (`client_id`),
KEY `fk_qsales_sale_employee1_idx` (`created_by`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=51 ;
then i want to add a foreign key
I try:
1.
alter table bd1.invoice
add foreign key fk_invoice_qsales_sale1(qsales_sale_id)
references db2.qsales_sale (qsales_sale_id)
on delete cascade
on update cascade;
ALTER TABLE db1.invoice
ADD CONSTRAINT fk_invoice_qsales_sale1 FOREIGN KEY (qsales_sale_id)
REFERENCES db2.qsales_sale (qsales_sale_id) ON DELETE NO ACTION ON UPDATE NO ACTION;
But i have this error:
Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (`qfix`.`#sql-a28_5`, CONSTRAINT `#sql-a28_5_ibfk_1` FOREIGN KEY (`qsales_sale_id`) REFERENCES `qsales`.`qsales_sale` (`qsales_sale_id`) ON DELETE CASCADE ON UPDATE CASCADE)
0.625 sec

Mysql add foreign key constraint fails

I'm trying to add a foreign key constraint on my schema devair from field user_id of table bluePrints to the PK id of table users but I get an error:
ERROR 1215: Cannot add foreign key constraint
Here are my table definitions:
users:
CREATE TABLE `users` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`password` varchar(60) COLLATE utf8_unicode_ci NOT NULL,
`remember_token` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `users_email_unique` (`email`)
) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
bluePrints:
CREATE TABLE `bluePrints` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`bluePrintName` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`description` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`user_id` int(10) NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `uid` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
And the offending alter table statement:
ALTER TABLE `devair`.`bluePrints`
ADD CONSTRAINT `bp_u`
FOREIGN KEY (user_id)
REFERENCES `devair`.`users` (id)
ON DELETE CASCADE
ON UPDATE CASCADE;
The simple answer would be that you need to do this:
ALTER TABLE table1 ADD CONSTRAINT fk_bp_id FOREIGN KEY (columnFromTable1) REFERENCES table2(columnReferencedFromTable2);
The problem is the 'unsigned' in the bluePrints table. Once it's unsigned, then it works.
Now i have to figure out how to get laravel to use unsigned.

What Is Possible Use One Reference Field To Multiple Foreign Key Constraint

I want to make 3 Tables like this :
wc_groups Table
CREATE TABLE IF NOT EXISTS `wc_groups` (
`id` int(2) unsigned NOT NULL AUTO_INCREMENT,
`idgroup` int(7) NOT NULL,
`title` varchar(10) NOT NULL,
`content` text,
`status` smallint(1) NOT NULL DEFAULT '1',
PRIMARY KEY (`id`),
UNIQUE KEY `idgroup` (`idgroup`),
KEY `status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
wc_matches Table
CREATE TABLE IF NOT EXISTS `wc_matches` (
`id` int(4) unsigned NOT NULL AUTO_INCREMENT,
`time` date NOT NULL,
`group_id` int(2) unsigned NOT NULL,
`place` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`team_id_1` int(10) unsigned NOT NULL,
`team_id_2` int(10) unsigned NOT NULL,
`edituser` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`),
KEY `group_id_foreign` (`group_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;
wc_teams Table
CREATE TABLE IF NOT EXISTS `wc_teams` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`group_id` int(2) unsigned NOT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;
ALTER TABLE `wc_teams`
ADD CONSTRAINT `group_id_foreign` FOREIGN KEY (`group_id`) REFERENCES `wc_groups` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
Why i got an error when execution Code to create table wc_team ?
What's possible to use What Is Possible Use One Reference Field ( wc_groups (id) ) To Multiple Foreign Key Constraint ?
I don't understand what you mean with multiple foreign keys.
But the problem in your wc_teams create query is that you have a lost , behind
`group_id` int(2) unsigned NOT NULL,
But you also miss your primary key so i guess you need this
CREATE TABLE IF NOT EXISTS `wc_teams` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`group_id` int(2) unsigned NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;