if with mysql results in syntax error - mysql

I need to use a if statment in my mysql trigger. It looks like that:
set #countentry = (SELECT count(id) as `id` FROM `tsc_page_have_wildcard` where idwildcard=1 and idpage=5);
IF #countentry <> 0 THEN
INSERT INTO `tsc_page_have_wildcard` (`idpage`, `idwildcard`) VALUES (#pageid, NEW.id);
END IF
By executing the trigger i get:
Error Code: 1064. You have an error
in your SQL syntax; check the manual that corresponds to your MySQL
server version for the right syntax to use near 'IF #countentry <> 0
THEN
INSERT INTO `tsc_page_have_wildcard` (`i' at line 1
The table struct is the following:
CREATE TABLE IF NOT EXISTS `tsc_page_have_wildcard` (
`id` int(11) NOT NULL auto_increment,
`idpage` int(11) NOT NULL,
`idwildcard` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `idpage` (`idpage`,`idwildcard`),
KEY `idwildcard` (`idwildcard`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=8 ;
ALTER TABLE `tsc_page_have_wildcard`
ADD CONSTRAINT `tsc_page_have_wildcard_ibfk_1` FOREIGN KEY (`idpage`) REFERENCES `tsc_page` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `tsc_page_have_wildcard_ibfk_2` FOREIGN KEY (`idwildcard`) REFERENCES `tsc_wildcard` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
INSERT INTO `tsc_page_have_wildcard` (`id`, `idpage`, `idwildcard`) VALUES
(1, 1, 1),
(2, 1, 2),
(3, 1, 3),
(4, 1, 4),
(5, 1, 5),
(6, 41, 4),
(7, 41, 5);
Does anyone know why this if statment isnt working in my trigger?

This code should work:
DELIMITER $$
CREATE /*!50017 DEFINER = 'root'#'localhost' */ TRIGGER `win` AFTER INSERT
ON `tsc_page_have_wildcard` FOR EACH ROW
BEGIN
SET #countentry =
(SELECT
COUNT(id) AS `id`
FROM
`tsc_page_have_wildcard`
WHERE idwildcard = 1
AND idpage = 5) ;
IF #countentry <> 0
THEN
INSERT INTO `tsc_page_have_wildcard` (`idpage`, `idwildcard`)
VALUES
(#pageid, NEW.id) ;
END IF ;
END $$
DELIMITER ;
Semi-colon(;) after END IF :-)

Related

How to find count in many to many relationship in MySql, Cakephp 3.6

I need to calculate the count(vendors.id) for each category.
ie: how many vendors are there for each category(not sub-category)
I am using cakephp 3.6 framework and MySQL as database
I tried with all possible way that i knew but not found any solution. Can anybody help me, is very important for my project
[UPDATE]
sql query i have used:
SELECT cat.id,cat.name ,COUNT(`vendor_id`) AS vendor_count FROM `vendor_services` JOIN `categories` ON(`vendor_services`.`category_id` = `categories`.`id`) JOIN `categories` AS cat ON(categories.category_id = cat.id) WHERE 1 GROUP BY cat.id
[UPDATE]Bellow is the sql to create corresponding tables
-- phpMyAdmin SQL Dump
-- version 4.7.0
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Dec 04, 2018 at 10:50 AM
-- Server version: 10.1.24-MariaDB
-- PHP Version: 7.1.6
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
--
-- Database: `demo123`
--
-- --------------------------------------------------------
--
-- Table structure for table `categories`
--
CREATE TABLE `categories` (
`id` int(11) NOT NULL,
`category_id` tinyint(4) NOT NULL,
`name` varchar(60) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `categories`
--
INSERT INTO `categories` (`id`, `category_id`, `name`) VALUES
(1, 0, 'Books'),
(2, 0, 'Electronics'),
(3, 0, 'Garden'),
(4, 1, 'Novel'),
(5, 1, 'Science'),
(6, 1, 'Story'),
(7, 2, 'Mobile'),
(8, 2, 'Tablet'),
(9, 2, 'Headphone'),
(10, 3, 'Pumps'),
(11, 3, 'Pipes');
-- --------------------------------------------------------
--
-- Table structure for table `vendors`
--
CREATE TABLE `vendors` (
`id` int(11) NOT NULL,
`name` varchar(60) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `vendors`
--
INSERT INTO `vendors` (`id`, `name`) VALUES
(1, 'VR Enterprizes'),
(2, 'RR Vendors'),
(3, 'JK Suppliers');
-- --------------------------------------------------------
--
-- Table structure for table `vendor_services`
--
CREATE TABLE `vendor_services` (
`id` int(11) NOT NULL,
`vendor_id` int(11) NOT NULL,
`category_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `vendor_services`
--
INSERT INTO `vendor_services` (`id`, `vendor_id`, `category_id`) VALUES
(1, 1, 4),
(2, 1, 5),
(3, 1, 6),
(4, 1, 11),
(5, 2, 7),
(6, 2, 8),
(7, 2, 9),
(8, 3, 10),
(9, 3, 11);
--
-- Indexes for dumped tables
--
--
-- Indexes for table `categories`
--
ALTER TABLE `categories`
ADD PRIMARY KEY (`id`),
ADD KEY `category_id` (`category_id`);
--
-- Indexes for table `vendors`
--
ALTER TABLE `vendors`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `vendor_services`
--
ALTER TABLE `vendor_services`
ADD PRIMARY KEY (`id`),
ADD KEY `vendor_id` (`vendor_id`),
ADD KEY `category_id` (`category_id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `categories`
--
ALTER TABLE `categories`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=12;
--
-- AUTO_INCREMENT for table `vendors`
--
ALTER TABLE `vendors`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT for table `vendor_services`
--
ALTER TABLE `vendor_services`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;COMMIT;
CategoriesTable
$this->hasMany(‘Subcategories’, [ 'className'=> ‘Categories’,
'foreignKey' => 'category_id',
'conditions' => ['category_id!= 0']
]);
$this->belongsTo('MainCategories', [
'className'=> ‘Categories’,
'foreignKey' => 'category_id',
]);
Below is the query in oracle, please have a look, and modify it as per mysql,
added below insertion,
INSERT INTO VENDOR_SERVICES (ID, VENDOR_ID, CATEGORY_ID)
VALUES(11, 3, 3);
SELECT FRM.CATEGORY_ID, FRM.VENDOR_ID, FRM.VENDER_NAME,COUNT(VENDOR_ID) counts FROM (
SELECT distinct CT.CATEGORY_ID, VS.VENDOR_ID, VS.CATEGORY_ID VS_CATEGORY_ID,vn.ID, vn.NAME VENDER_NAME FROM CATEGORIES CT
INNER JOIN VENDOR_SERVICES VS ON VS.CATEGORY_ID=CT.CATEGORY_ID
INNER JOIN VENDORS VN ON VS.VENDOR_ID=VN.ID) frm
group by CATEGORY_ID, VENDOR_ID, VENDER_NAME

Can't create table 'e-learningsystem.chapter' (errno: 121) [duplicate]

I have troubles with forward engineering my MySQL database into WAMP server..
I was going to post an image of the schema but as this is my first post I can't.
Below is the executed script..
use aquaticstar;
SET #OLD_UNIQUE_CHECKS=##UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET #OLD_FOREIGN_KEY_CHECKS=##FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET #OLD_SQL_MODE=##SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';
-- -----------------------------------------------------
-- Table `Students`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `Students` ;
CREATE TABLE IF NOT EXISTS `Students` (
`id` VARCHAR(10) NOT NULL ,
`studentName` VARCHAR(45) NOT NULL ,
`gender` CHAR NOT NULL ,
`birthDate` DATETIME NOT NULL ,
`mNo` VARCHAR(10) NOT NULL ,
`contactName` VARCHAR(45) NOT NULL ,
`contactEmail` VARCHAR(45) NOT NULL ,
`contactPhone` INT(10) NOT NULL ,
`startDate` DATETIME NOT NULL ,
`remarks` VARCHAR(200) NULL ,
PRIMARY KEY (`id`) )
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `Waiting List`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `Waiting List` ;
CREATE TABLE IF NOT EXISTS `Waiting List` (
`wait_id` VARCHAR(5) NOT NULL ,
`name` VARCHAR(45) NULL ,
`contactName` VARCHAR(45) NULL ,
`contactPhone` INT(10) NULL ,
`contactEmail` VARCHAR(45) NULL ,
`status` CHAR NULL ,
`remarks` VARCHAR(200) NULL ,
PRIMARY KEY (`wait_id`) )
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `Schedule`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `Schedule` ;
CREATE TABLE IF NOT EXISTS `Schedule` (
`lesson_id` VARCHAR(10) NOT NULL ,
`day` VARCHAR(3) NOT NULL ,
`branch` VARCHAR(30) NOT NULL ,
`level` VARCHAR(30) NOT NULL ,
`time` TIME NOT NULL ,
`ae` VARCHAR(45) NOT NULL ,
PRIMARY KEY (`lesson_id`) )
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `Link`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `Link` ;
CREATE TABLE IF NOT EXISTS `Link` (
`link_id` VARCHAR(10) NOT NULL ,
`id` VARCHAR(10) NOT NULL ,
`lesson_id` VARCHAR(10) NOT NULL ,
PRIMARY KEY (`link_id`) ,
INDEX `id_idx` (`id` ASC) ,
INDEX `lesson_id_idx` (`lesson_id` ASC) ,
CONSTRAINT `id`
FOREIGN KEY (`id` )
REFERENCES `Students` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `lesson_id`
FOREIGN KEY (`lesson_id` )
REFERENCES `Schedule` (`lesson_id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `Attendance`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `Attendance` ;
CREATE TABLE IF NOT EXISTS `Attendance` (
`date` DATETIME NOT NULL ,
`attendance` VARCHAR(5) NOT NULL ,
`link_id` VARCHAR(10) NOT NULL ,
INDEX `link_id_idx` (`link_id` ASC) ,
CONSTRAINT `link_id`
FOREIGN KEY (`link_id` )
REFERENCES `Link` (`link_id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
SET SQL_MODE=#OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=#OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=#OLD_UNIQUE_CHECKS;
-- -----------------------------------------------------
-- Data for table `Students`
-- -----------------------------------------------------
START TRANSACTION;
INSERT INTO `Students` (`id`, `studentName`, `gender`, `birthDate`, `mNo`, `contactName`, `contactEmail`, `contactPhone`, `startDate`, `remarks`) VALUES ('s001', 'Sam Khew', 'm', '12/12/1991', 'nm', 'May Khew', 'may#gmail.com', 0198829387, '12/07/2011', NULL);
INSERT INTO `Students` (`id`, `studentName`, `gender`, `birthDate`, `mNo`, `contactName`, `contactEmail`, `contactPhone`, `startDate`, `remarks`) VALUES ('s002', 'Joe Biden', 'm', '13/03/2003', 'nm', 'Layla Biden', 'layla#gmail.com', 0199283763, '14/05/2011', NULL);
INSERT INTO `Students` (`id`, `studentName`, `gender`, `birthDate`, `mNo`, `contactName`, `contactEmail`, `contactPhone`, `startDate`, `remarks`) VALUES ('s003', 'Bob Builder', 'm', '14/02/2002', 'LK920K', 'Mama Builder', 'mama#yahoo.com', 0167728376, '29/02/2012', NULL);
INSERT INTO `Students` (`id`, `studentName`, `gender`, `birthDate`, `mNo`, `contactName`, `contactEmail`, `contactPhone`, `startDate`, `remarks`) VALUES ('s004', 'Kenny Koh', 'm', '18/02/1999', 'MM992', 'Lisa Koh', 'lk#hotmail.com', 0123160231, '19/01/2012', NULL);
INSERT INTO `Students` (`id`, `studentName`, `gender`, `birthDate`, `mNo`, `contactName`, `contactEmail`, `contactPhone`, `startDate`, `remarks`) VALUES ('s005', 'Jane Doe', 'f', '29/09/1999', 'nm', 'Jackie Doe', 'jackied#gmail.com', 0127736254, '02/03/2012', NULL);
INSERT INTO `Students` (`id`, `studentName`, `gender`, `birthDate`, `mNo`, `contactName`, `contactEmail`, `contactPhone`, `startDate`, `remarks`) VALUES ('s006', 'Lola Lai', 'f', '02/05/2004', 'nm', 'Mark Lai', 'mark#gmail.com', 0198827365, '11/09/2011', NULL);
COMMIT;
-- -----------------------------------------------------
-- Data for table `Schedule`
-- -----------------------------------------------------
START TRANSACTION;
INSERT INTO `Schedule` (`lesson_id`, `day`, `branch`, `level`, `time`, `ae`) VALUES ('sat1_s4', 'Sat', 'Sunway', 'basic', '4pm', 'Aini');
INSERT INTO `Schedule` (`lesson_id`, `day`, `branch`, `level`, `time`, `ae`) VALUES ('sat1_s5', 'Sat', 'Sunway', 'basic', '5pm', 'Aini');
INSERT INTO `Schedule` (`lesson_id`, `day`, `branch`, `level`, `time`, `ae`) VALUES ('sat1_s6', 'Sat', 'Sunway', 'basic', '6pm', 'Aini');
INSERT INTO `Schedule` (`lesson_id`, `day`, `branch`, `level`, `time`, `ae`) VALUES ('sat2_s4', 'Sat', 'Sunway', 'advance', '4pm', 'Nina');
INSERT INTO `Schedule` (`lesson_id`, `day`, `branch`, `level`, `time`, `ae`) VALUES ('sat2_s5', 'Sat', 'Sunway', 'advance', '5pm', 'Nina');
INSERT INTO `Schedule` (`lesson_id`, `day`, `branch`, `level`, `time`, `ae`) VALUES ('sat3_s6', 'Sat', 'Sunway', 'pre-comp', '6pm', 'Marcus');
COMMIT;
-- -----------------------------------------------------
-- Data for table `Link`
-- -----------------------------------------------------
START TRANSACTION;
INSERT INTO `Link` (`link_id`, `id`, `lesson_id`) VALUES ('L001', 's001', 'sat1_s4');
INSERT INTO `Link` (`link_id`, `id`, `lesson_id`) VALUES ('L002', 's002', 'sat1_s5');
INSERT INTO `Link` (`link_id`, `id`, `lesson_id`) VALUES ('L003', 's003', 'sat1_s6');
INSERT INTO `Link` (`link_id`, `id`, `lesson_id`) VALUES ('L004', 's004', 'sat2_s4');
INSERT INTO `Link` (`link_id`, `id`, `lesson_id`) VALUES ('L005', 's005', 'sat1_s5');
COMMIT;
-- -----------------------------------------------------
-- Data for table `Attendance`
-- -----------------------------------------------------
START TRANSACTION;
INSERT INTO `Attendance` (`date`, `attendance`, `link_id`) VALUES ('26/9/2012', '1', NULL);
COMMIT;
But then I get this error:
Executing SQL script in server
ERROR: Error 1005: Can't create table 'aquaticstar.link' (errno: 121)
I can't figure out why. Can anyone help me?
I searched quickly for you, and it brought me here. I quote:
You will get this message if you're trying to add a constraint with a
name that's already used somewhere else
To check constraints use the following SQL query:
SELECT
constraint_name,
table_name
FROM
information_schema.table_constraints
WHERE
constraint_type = 'FOREIGN KEY'
AND table_schema = DATABASE()
ORDER BY
constraint_name;
Look for more information there, or try to see where the error occurs. Looks like a problem with a foreign key to me.
Foreign Key Constraint Names Have to be Unique Within a Database
Both #Dorvalla’s answer and this blog post mentioned above pointed me into the right direction to fix the problem for myself; quoting from the latter:
If the table you're trying to create includes a foreign key constraint, and you've provided your own name for that constraint, remember that it must be unique within the database.
I wasn’t aware of that. I have changed my foreign key constraint names according to the following schema which appears to be used by Ruby on Rails applications, too:
<TABLE_NAME>_<FOREIGN_KEY_COLUMN_NAME>_fk
For the OP’s table this would be Link_lession_id_fk, for example.
You can login to mysql and type
mysql> SHOW INNODB STATUS\G
You will have all the output and you should have a better idea of what the error is.
I faced this error (errno 121) but it was caused by mysql-created intermediate tables that had been orphaned, preventing me from altering a table even though no such constraint name existed across any of my tables. At some point, my MySQL had crashed or failed to cleanup an intermediate table (table name starting with a #sql-) which ended up presenting me with an error such as: Can't create table '#sql-' (errno 121) when trying to run an ALTER TABLE with certain constraint names.
According to the docs at http://dev.mysql.com/doc/refman/5.7/en/innodb-troubleshooting-datadict.html , you can search for these orphan tables with:
SELECT * FROM INFORMATION_SCHEMA.INNODB_SYS_TABLES WHERE NAME LIKE '%#sql%';
The version I was working with was 5.1, but the above command only works on versions >= 5.6 (manual is incorrect about it working for 5.5 or earlier, because INNODB_SYS_TABLES does not exist in such versions). I was able to find the orphaned temporary table (which did not match the one named in the message) by searching my mysql data directory in command line:
find . -iname '#*'
After discovering the filename, such as #sql-9ad_15.frm, I was able to drop that orphaned table in MySQL:
USE myschema;
DROP TABLE `#mysql50##sql-9ad_15`;
After doing so, I was then able to successfully run my ALTER TABLE.
For completeness, as per the MySQL documentation linked, "the #mysql50# prefix tells MySQL to ignore file name safe encoding introduced in MySQL 5.1."
If you have a foreign key definition in some table and the name of the foreign key is used elsewhere as another foreign key you will have this error.
If you want to fix quickly, Forward Engineer again and check "Generate DROP SCHEMA" option and proceed.
I assume the database doesn't contain data, so dropping it won't affect.
Something I noticed was that I had "other_database" and "Other_Database" in my databases.
That caused this problem as I actually had same reference in other database which caused this mysterious error!
mysql> SHOW ENGINE INNODB STATUS;
But in my case only this way could help:
1. Make backup of current DB
2. Drop DB (not all tables, but DB)
3. Create DB (check that you still have previleges)
4. Restore DB from backup

mySQL that gets entries from another table using Foreign Keys?

Here are my tables:
class
-------
classId
course //example: CMSC101
semester //example: Spring 2013
profId
professor
---------
profId
lname
fname
I want to find all the courses where all the professors with the last name Smith teaches. I essentially want to do this:
SELECT * FROM `professor` WHERE lname=`Smith`
Then, take those results and insert them where the ??? is:
SELECT * FROM `class` WHERE profId=`???`
Is there anyway I can do this with just one query?
I strongly recommend you to use SQL JOINS. You learn once, and use throughout your entire life.
SELECT c.*
FROM class AS c
INNER JOIN professor AS p
ON (c.profId = p.profId)
WHERE p.lname LIKE 'Smith';
Some readings for you:
SQL Joins
Database Normalization
[update]
Small gift for you:
SET #OLD_UNIQUE_CHECKS=##UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET #OLD_FOREIGN_KEY_CHECKS=##FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET #OLD_SQL_MODE=##SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';
DROP SCHEMA IF EXISTS `school` ;
CREATE SCHEMA IF NOT EXISTS `school` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ;
USE `school` ;
-- -----------------------------------------------------
-- Table `school`.`professor`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `school`.`professor` (
`professorId` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`lname` VARCHAR(40) NOT NULL ,
`fname` VARCHAR(40) NOT NULL ,
PRIMARY KEY (`professorId`) )
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `school`.`semester`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `school`.`semester` (
`semesterId` TINYINT UNSIGNED NOT NULL AUTO_INCREMENT ,
`name` VARCHAR(8) NOT NULL ,
PRIMARY KEY (`semesterId`) )
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `school`.`course`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `school`.`course` (
`courseId` TINYINT UNSIGNED NOT NULL AUTO_INCREMENT ,
`code` VARCHAR(10) NOT NULL ,
`name` VARCHAR(40) NOT NULL ,
PRIMARY KEY (`courseId`) ,
UNIQUE INDEX `code_UNIQUE` (`code` ASC) )
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `school`.`class`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `school`.`class` (
`classId` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`courseId` TINYINT UNSIGNED NOT NULL ,
`semesterId` TINYINT UNSIGNED NOT NULL ,
`profId` INT UNSIGNED NOT NULL ,
PRIMARY KEY (`classId`) ,
INDEX `fk_class_professor_idx` (`profId` ASC) ,
INDEX `fk_class_semester1_idx` (`semesterId` ASC) ,
INDEX `fk_class_course1_idx` (`courseId` ASC) ,
CONSTRAINT `fk_class_professor`
FOREIGN KEY (`profId` )
REFERENCES `school`.`professor` (`professorId` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_class_semester1`
FOREIGN KEY (`semesterId` )
REFERENCES `school`.`semester` (`semesterId` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_class_course1`
FOREIGN KEY (`courseId` )
REFERENCES `school`.`course` (`courseId` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
USE `school` ;
-- -----------------------------------------------------
-- Placeholder table for view `school`.`class_details`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `school`.`class_details` (`class_id` INT, `course_id` INT, `course_code` INT, `course_name` INT, `semester_id` INT, `semester_name` INT, `prof_id` INT, `prof_fname` INT, `prof_lname` INT);
-- -----------------------------------------------------
-- View `school`.`class_details`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `school`.`class_details`;
USE `school`;
CREATE OR REPLACE VIEW `school`.`class_details` AS
SELECT
w.classId AS `class_id`,
w.courseId AS `course_id`,
x.`code` AS `course_code`,
x.`name` AS `course_name`,
w.semesterId AS `semester_id`,
y.`name` AS `semester_name`,
w.profId AS `prof_id`,
z.fname AS `prof_fname`,
z.lname AS `prof_lname`
FROM class AS w
INNER JOIN course AS x
ON (w.courseId = x.courseId)
INNER JOIN semester AS y
ON (w.semesterId = y.semesterId)
INNER JOIN professor AS z
ON (w.profId = z.professorId);
SET SQL_MODE=#OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=#OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=#OLD_UNIQUE_CHECKS;
-- -----------------------------------------------------
-- Data for table `school`.`professor`
-- -----------------------------------------------------
START TRANSACTION;
USE `school`;
INSERT INTO `school`.`professor` (`professorId`, `lname`, `fname`) VALUES (1, 'Smith', 'Willard');
INSERT INTO `school`.`professor` (`professorId`, `lname`, `fname`) VALUES (2, 'Burton', 'Tim');
COMMIT;
-- -----------------------------------------------------
-- Data for table `school`.`semester`
-- -----------------------------------------------------
START TRANSACTION;
USE `school`;
INSERT INTO `school`.`semester` (`semesterId`, `name`) VALUES (1, '2011.1');
INSERT INTO `school`.`semester` (`semesterId`, `name`) VALUES (2, '2011.2');
INSERT INTO `school`.`semester` (`semesterId`, `name`) VALUES (3, '2012.1');
INSERT INTO `school`.`semester` (`semesterId`, `name`) VALUES (4, '2012.2');
INSERT INTO `school`.`semester` (`semesterId`, `name`) VALUES (5, '2013.1');
INSERT INTO `school`.`semester` (`semesterId`, `name`) VALUES (6, '2013.2');
INSERT INTO `school`.`semester` (`semesterId`, `name`) VALUES (7, '2014.1');
INSERT INTO `school`.`semester` (`semesterId`, `name`) VALUES (8, '2014.2');
COMMIT;
-- -----------------------------------------------------
-- Data for table `school`.`course`
-- -----------------------------------------------------
START TRANSACTION;
USE `school`;
INSERT INTO `school`.`course` (`courseId`, `code`, `name`) VALUES (1, 'CALC1', 'Calculus 1');
INSERT INTO `school`.`course` (`courseId`, `code`, `name`) VALUES (2, 'CALC2', 'Calculus 2');
INSERT INTO `school`.`course` (`courseId`, `code`, `name`) VALUES (3, 'PHYS1', 'Physics 1');
INSERT INTO `school`.`course` (`courseId`, `code`, `name`) VALUES (4, 'PHYS2', 'Physics 2');
COMMIT;
-- -----------------------------------------------------
-- Data for table `school`.`class`
-- -----------------------------------------------------
START TRANSACTION;
USE `school`;
INSERT INTO `school`.`class` (`classId`, `courseId`, `semesterId`, `profId`) VALUES (1, 1, 3, 1);
INSERT INTO `school`.`class` (`classId`, `courseId`, `semesterId`, `profId`) VALUES (2, 2, 3, 1);
INSERT INTO `school`.`class` (`classId`, `courseId`, `semesterId`, `profId`) VALUES (3, 3, 3, 2);
INSERT INTO `school`.`class` (`classId`, `courseId`, `semesterId`, `profId`) VALUES (4, 4, 3, 2);
INSERT INTO `school`.`class` (`classId`, `courseId`, `semesterId`, `profId`) VALUES (5, 1, 4, 1);
INSERT INTO `school`.`class` (`classId`, `courseId`, `semesterId`, `profId`) VALUES (6, 2, 4, 1);
INSERT INTO `school`.`class` (`classId`, `courseId`, `semesterId`, `profId`) VALUES (7, 3, 4, 2);
INSERT INTO `school`.`class` (`classId`, `courseId`, `semesterId`, `profId`) VALUES (8, 4, 4, 2);
COMMIT;
SELECT * FROM class_details;
SELECT * FROM class_details WHERE prof_lname LIKE 'Smith';
This should work:
SELECT a.* FROM class a, professor b WHERE a.profId = b.profId AND b.lname = 'Smith';
Cheers.

mysql trigger insert in multiple table by condition

I want to split rows using trigger, to 2 different tables if rows are more then 5 then insert only 5 rows to table leave and others rows to table nonpay_leave . I have a working trigger which insert rows only in one (I included trigger and my database code at the bottom of question).
currently working trigger
I have a table called staff_leave_application which have this columns :
id_staff_leave_application | staff_id_staff | leave_type_id_leave_type | start_date | end_date | joining_date
and it has a trigger called tn_air_staff_leave_application:
DELIMITER $$
USE `mydb`$$
CREATE
DEFINER=`root`#`localhost`
TRIGGER `mydb`.`tn_air_staff_leave_application`
AFTER INSERT ON `mydb`.`staff_leave_application`
FOR EACH ROW
BEGIN
SET #counter := -1;
WHILE (#counter < DATEDIFF(DATE(new.end_date), DATE(new.start_date))) DO
INSERT INTO `leave`(staff_leave_application_id_staff_leave_application, staff_leave_application_staff_id_staff, leave_type_id_leave_type, date, active, date_updated)
VALUES (new.id_staff_leave_application, new.staff_id_staff, new.leave_type_id_leave_type, DATE_ADD(new.start_date, INTERVAL #counter:=#counter + 1 DAY), 1, CURDATE());
END WHILE;
END$$
what above trigger actually do?
This trigger run after insert on staff_leave_application. The trigger split currently inserted row in staff_leave_application by per day per row from date range and then insert rows to the table called leave each day per row.
Then, What i want actually ???
I want to change this trigger, so that if new rows are more then 5 then insert other rows to another table called nonpay_leave. like:
if trigger generates 7 rows, then insert first 5 rows to table leave and other 2 rows to table nonpay_leave.
My database structure
--
-- Table structure for table `designation`
--
CREATE TABLE IF NOT EXISTS `designation` (
`id_designation` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(45) NOT NULL,
PRIMARY KEY (`id_designation`),
UNIQUE KEY `id_designation_UNIQUE` (`id_designation`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=14 ;
--
-- Dumping data for table `designation`
--
INSERT INTO `designation` (`id_designation`, `name`) VALUES
(10, 'Manager'),
(12, 'Medical Officer'),
(13, 'Peon');
-- --------------------------------------------------------
--
-- Table structure for table `leave`
--
CREATE TABLE IF NOT EXISTS `leave` (
`id_leave` int(11) NOT NULL AUTO_INCREMENT,
`staff_leave_application_id_staff_leave_application` int(11) NOT NULL,
`staff_leave_application_staff_id_staff` int(11) NOT NULL,
`leave_type_id_leave_type` int(11) NOT NULL,
`date` date NOT NULL,
`active` int(11) NOT NULL DEFAULT '1',
`date_updated` date NOT NULL,
PRIMARY KEY (`id_leave`,`staff_leave_application_id_staff_leave_application`,`staff_leave_application_staff_id_staff`),
KEY `fk_table1_leave_type1` (`leave_type_id_leave_type`),
KEY `fk_table1_staff_leave_application1` (`staff_leave_application_id_staff_leave_application`,`staff_leave_application_staff_id_staff`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=32 ;
--
-- Dumping data for table `leave`
--
INSERT INTO `leave` (`id_leave`, `staff_leave_application_id_staff_leave_application`, `staff_leave_application_staff_id_staff`, `leave_type_id_leave_type`, `date`, `active`, `date_updated`) VALUES
(21, 12, 7, 8, '2013-01-22', 1, '2013-01-21'),
(22, 12, 7, 8, '2013-01-23', 1, '2013-01-21'),
(23, 12, 7, 8, '2013-01-24', 1, '2013-01-21'),
(24, 12, 7, 8, '2013-01-25', 1, '2013-01-21'),
(25, 13, 7, 9, '2013-01-30', 1, '2013-01-21'),
(26, 13, 7, 9, '2013-01-31', 1, '2013-01-21'),
(27, 14, 7, 8, '2013-02-11', 1, '2013-01-21'),
(28, 14, 7, 8, '2013-02-12', 1, '2013-01-21'),
(29, 14, 7, 8, '2013-02-13', 1, '2013-01-21'),
(30, 14, 7, 8, '2013-02-14', 1, '2013-01-21'),
(31, 14, 7, 8, '2013-02-15', 1, '2013-01-21');
-- --------------------------------------------------------
--
-- Table structure for table `leave_allowed`
--
CREATE TABLE IF NOT EXISTS `leave_allowed` (
`id_leave_allowed` int(11) NOT NULL AUTO_INCREMENT,
`staff_id_staff` int(11) NOT NULL,
`leave_type_id_leave_type` int(11) NOT NULL,
`days` float NOT NULL,
PRIMARY KEY (`id_leave_allowed`),
UNIQUE KEY `id_leave_allowed_UNIQUE` (`id_leave_allowed`),
KEY `fk_leave_allowed_staff1` (`staff_id_staff`),
KEY `fk_leave_allowed_leave_type1` (`leave_type_id_leave_type`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
--
-- Dumping data for table `leave_allowed`
--
INSERT INTO `leave_allowed` (`id_leave_allowed`, `staff_id_staff`, `leave_type_id_leave_type`, `days`) VALUES
(1, 7, 8, 2.5),
(2, 7, 9, 200);
-- --------------------------------------------------------
--
-- Table structure for table `leave_app_view`
--
CREATE ALGORITHM=UNDEFINED DEFINER=`1`#`localhost` SQL SECURITY DEFINER VIEW `mydb`.`leave_app_view` AS select `mydb`.`staff`.`name` AS `name`,`mydb`.`staff`.`file_no` AS `file_no`,`mydb`.`staff`.`photo` AS `photo`,`mydb`.`staff_leave_application`.`leave_type_id_leave_type` AS `leave_type_id_leave_type`,`mydb`.`staff_leave_application`.`start_date` AS `start_date`,`mydb`.`staff_leave_application`.`end_date` AS `end_date`,`mydb`.`staff_leave_application`.`joining_date` AS `joining_date` from (`mydb`.`staff` join `mydb`.`staff_leave_application` on((`mydb`.`staff`.`id_staff` = `mydb`.`staff_leave_application`.`staff_id_staff`)));
--
-- Dumping data for table `leave_app_view`
--
INSERT INTO `leave_app_view` (`name`, `file_no`, `photo`, `leave_type_id_leave_type`, `start_date`, `end_date`, `joining_date`) VALUES
('Rahul Ayan', '54', NULL, 8, '2013-01-22', '2013-01-25', '2013-01-26'),
('Rahul Ayan', '54', NULL, 9, '2013-01-30', '2013-01-31', '2013-02-01'),
('Rahul Ayan', '54', NULL, 8, '2013-02-11', '2013-02-15', '2013-02-16');
-- --------------------------------------------------------
--
-- Table structure for table `leave_balance`
--
CREATE TABLE IF NOT EXISTS `leave_balance` (
`id_leave_balance` int(11) NOT NULL AUTO_INCREMENT,
`staff_id_staff` int(11) NOT NULL,
`leave_type_id_leave_type` int(11) NOT NULL,
`balance` int(3) NOT NULL,
`date_added` date NOT NULL,
PRIMARY KEY (`id_leave_balance`),
UNIQUE KEY `id_leave_balance_UNIQUE` (`id_leave_balance`),
KEY `fk_leave_balance_staff1` (`staff_id_staff`),
KEY `fk_leave_balance_leave_type1` (`leave_type_id_leave_type`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
--
-- Dumping data for table `leave_balance`
--
INSERT INTO `leave_balance` (`id_leave_balance`, `staff_id_staff`, `leave_type_id_leave_type`, `balance`, `date_added`) VALUES
(1, 7, 8, 230, '2013-01-21'),
(2, 7, 9, 200, '2013-01-21');
-- --------------------------------------------------------
--
-- Table structure for table `leave_balance_view`
--
CREATE ALGORITHM=UNDEFINED DEFINER=`1`#`localhost` SQL SECURITY DEFINER VIEW `mydb`.`leave_balance_view` AS select `mydb`.`leave_balance`.`staff_id_staff` AS `staff_id_staff`,`leave_taken`.`leave_type_id_leave_type` AS `leave_type_id_leave_type`,(`mydb`.`leave_balance`.`balance` - `leave_taken`.`days`) AS `new_balance`,`mydb`.`leave_balance`.`date_added` AS `date_added` from ((`mydb`.`staff` join `mydb`.`leave_taken` on((`mydb`.`staff`.`id_staff` = `leave_taken`.`staff_leave_application_staff_id_staff`))) join `mydb`.`leave_balance` on(((`leave_taken`.`staff_leave_application_staff_id_staff` = `mydb`.`leave_balance`.`staff_id_staff`) and (`leave_taken`.`leave_type_id_leave_type` = `mydb`.`leave_balance`.`leave_type_id_leave_type`))));
--
-- Dumping data for table `leave_balance_view`
--
INSERT INTO `leave_balance_view` (`staff_id_staff`, `leave_type_id_leave_type`, `new_balance`, `date_added`) VALUES
(7, 8, 221, '2013-01-21'),
(7, 9, 198, '2013-01-21');
-- --------------------------------------------------------
--
-- Table structure for table `leave_taken`
--
CREATE ALGORITHM=UNDEFINED DEFINER=`1`#`localhost` SQL SECURITY DEFINER VIEW `mydb`.`leave_taken` AS select `mydb`.`leave`.`staff_leave_application_staff_id_staff` AS `staff_leave_application_staff_id_staff`,`mydb`.`leave`.`leave_type_id_leave_type` AS `leave_type_id_leave_type`,count(0) AS `days` from (`mydb`.`leave` join `mydb`.`staff` on((`mydb`.`staff`.`id_staff` = `mydb`.`leave`.`staff_leave_application_staff_id_staff`))) where (`mydb`.`leave`.`active` = 1) group by `mydb`.`leave`.`leave_type_id_leave_type`;
--
-- Dumping data for table `leave_taken`
--
INSERT INTO `leave_taken` (`staff_leave_application_staff_id_staff`, `leave_type_id_leave_type`, `days`) VALUES
(7, 8, 9),
(7, 9, 2);
-- --------------------------------------------------------
--
-- Table structure for table `leave_type`
--
CREATE TABLE IF NOT EXISTS `leave_type` (
`id_leave_type` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(45) NOT NULL,
`paid` int(11) DEFAULT NULL,
PRIMARY KEY (`id_leave_type`),
UNIQUE KEY `id_leave_type_UNIQUE` (`id_leave_type`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ;
--
-- Dumping data for table `leave_type`
--
INSERT INTO `leave_type` (`id_leave_type`, `name`, `paid`) VALUES
(8, 'Casual Leave', NULL),
(9, 'Medical Leave', NULL);
-- --------------------------------------------------------
--
-- Table structure for table `nonpay_leave`
--
CREATE TABLE IF NOT EXISTS `nonpay_leave` (
`id_nonpay_leave` int(11) NOT NULL AUTO_INCREMENT,
`staff_leave_application_id_staff_leave_application` int(11) NOT NULL,
`staff_leave_application_staff_id_staff` int(11) NOT NULL,
`leave_type_id_leave_type` int(11) NOT NULL,
`leave_date` date DEFAULT NULL,
`active` int(1) DEFAULT NULL,
`date_updated` date DEFAULT NULL,
PRIMARY KEY (`id_nonpay_leave`,`staff_leave_application_id_staff_leave_application`,`staff_leave_application_staff_id_staff`),
KEY `fk_nonpay_leave_staff_leave_application1` (`staff_leave_application_id_staff_leave_application`,`staff_leave_application_staff_id_staff`),
KEY `fk_nonpay_leave_leave_type1` (`leave_type_id_leave_type`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
--
-- Dumping data for table `nonpay_leave`
--
-- --------------------------------------------------------
--
-- Table structure for table `staff`
--
CREATE TABLE IF NOT EXISTS `staff` (
`id_staff` int(11) NOT NULL AUTO_INCREMENT,
`file_no` varchar(45) NOT NULL,
`title_id_title` int(11) NOT NULL,
`name` varchar(80) NOT NULL,
`dob` date DEFAULT NULL,
`designation_id_designation` int(11) NOT NULL,
`status_id_status` int(11) NOT NULL,
`date_of_join` date DEFAULT NULL,
`photo` blob,
`user_name` varchar(10) DEFAULT NULL,
`password` varchar(10) DEFAULT NULL,
PRIMARY KEY (`id_staff`),
UNIQUE KEY `id_staff_UNIQUE` (`id_staff`),
KEY `fk_staff_title` (`title_id_title`),
KEY `fk_staff_designation1` (`designation_id_designation`),
KEY `fk_staff_status1` (`status_id_status`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=8 ;
--
-- Dumping data for table `staff`
--
INSERT INTO `staff` (`id_staff`, `file_no`, `title_id_title`, `name`, `dob`, `designation_id_designation`, `status_id_status`, `date_of_join`, `photo`, `user_name`, `password`) VALUES
(7, '54', 10, 'Rahul Ayan', '1991-09-14', 10, 6, '2012-01-02', NULL, NULL, NULL);
-- --------------------------------------------------------
--
-- Table structure for table `staff_leave_application`
--
CREATE TABLE IF NOT EXISTS `staff_leave_application` (
`id_staff_leave_application` int(11) NOT NULL AUTO_INCREMENT,
`staff_id_staff` int(11) NOT NULL,
`leave_type_id_leave_type` int(11) NOT NULL,
`start_date` date NOT NULL,
`end_date` date NOT NULL,
`joining_date` date NOT NULL,
PRIMARY KEY (`id_staff_leave_application`,`staff_id_staff`),
UNIQUE KEY `id_staff_leave_UNIQUE` (`id_staff_leave_application`),
KEY `fk_staff_leave_staff1` (`staff_id_staff`),
KEY `fk_staff_leave_leave_type1` (`leave_type_id_leave_type`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=15 ;
--
-- Dumping data for table `staff_leave_application`
--
INSERT INTO `staff_leave_application` (`id_staff_leave_application`, `staff_id_staff`, `leave_type_id_leave_type`, `start_date`, `end_date`, `joining_date`) VALUES
(12, 7, 8, '2013-01-22', '2013-01-25', '2013-01-26'),
(13, 7, 9, '2013-01-30', '2013-01-31', '2013-02-01'),
(14, 7, 8, '2013-02-11', '2013-02-15', '2013-02-16');
--
-- Triggers `staff_leave_application`
--
DROP TRIGGER IF EXISTS `tn_air_staff_leave_application`;
DELIMITER //
CREATE TRIGGER `tn_air_staff_leave_application` AFTER INSERT ON `staff_leave_application`
FOR EACH ROW BEGIN
SET #counter := -1;
WHILE (#counter < DATEDIFF(DATE(new.end_date), DATE(new.start_date))) DO
INSERT INTO `leave`(staff_leave_application_id_staff_leave_application, staff_leave_application_staff_id_staff, leave_type_id_leave_type, date, active, date_updated)
VALUES (new.id_staff_leave_application, new.staff_id_staff, new.leave_type_id_leave_type, DATE_ADD(new.start_date, INTERVAL #counter:=#counter + 1 DAY), 1, CURDATE());
END WHILE;
END
//
DELIMITER ;
-- --------------------------------------------------------
--
-- Table structure for table `status`
--
CREATE TABLE IF NOT EXISTS `status` (
`id_status` int(11) NOT NULL AUTO_INCREMENT,
`type` varchar(45) NOT NULL,
PRIMARY KEY (`id_status`),
UNIQUE KEY `id_ststus_UNIQUE` (`id_status`),
UNIQUE KEY `type_UNIQUE` (`type`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=8 ;
--
-- Dumping data for table `status`
--
INSERT INTO `status` (`id_status`, `type`) VALUES
(6, 'Contract'),
(7, 'Permanent');
-- --------------------------------------------------------
--
-- Table structure for table `title`
--
CREATE TABLE IF NOT EXISTS `title` (
`id_title` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(5) NOT NULL,
PRIMARY KEY (`id_title`),
UNIQUE KEY `id_title_UNIQUE` (`id_title`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=14 ;
--
-- Dumping data for table `title`
--
INSERT INTO `title` (`id_title`, `name`) VALUES
(10, 'Mr'),
(11, 'Dr'),
(12, 'Mrs'),
(13, 'Miss');
--
-- Constraints for dumped tables
--
--
-- Constraints for table `leave`
--
ALTER TABLE `leave`
ADD CONSTRAINT `fk_table1_leave_type1` FOREIGN KEY (`leave_type_id_leave_type`) REFERENCES `leave_type` (`id_leave_type`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `fk_table1_staff_leave_application1` FOREIGN KEY (`staff_leave_application_id_staff_leave_application`, `staff_leave_application_staff_id_staff`) REFERENCES `staff_leave_application` (`id_staff_leave_application`, `staff_id_staff`) ON DELETE CASCADE ON UPDATE NO ACTION;
--
-- Constraints for table `leave_allowed`
--
ALTER TABLE `leave_allowed`
ADD CONSTRAINT `fk_leave_allowed_leave_type1` FOREIGN KEY (`leave_type_id_leave_type`) REFERENCES `leave_type` (`id_leave_type`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `fk_leave_allowed_staff1` FOREIGN KEY (`staff_id_staff`) REFERENCES `staff` (`id_staff`) ON DELETE CASCADE ON UPDATE NO ACTION;
--
-- Constraints for table `leave_balance`
--
ALTER TABLE `leave_balance`
ADD CONSTRAINT `fk_leave_balance_leave_type1` FOREIGN KEY (`leave_type_id_leave_type`) REFERENCES `leave_type` (`id_leave_type`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `fk_leave_balance_staff1` FOREIGN KEY (`staff_id_staff`) REFERENCES `staff` (`id_staff`) ON UPDATE NO ACTION;
--
-- Constraints for table `nonpay_leave`
--
ALTER TABLE `nonpay_leave`
ADD CONSTRAINT `fk_nonpay_leave_staff_leave_application1` FOREIGN KEY (`staff_leave_application_id_staff_leave_application`, `staff_leave_application_staff_id_staff`) REFERENCES `staff_leave_application` (`id_staff_leave_application`, `staff_id_staff`) ON DELETE CASCADE ON UPDATE NO ACTION,
ADD CONSTRAINT `fk_nonpay_leave_leave_type1` FOREIGN KEY (`leave_type_id_leave_type`) REFERENCES `leave_type` (`id_leave_type`) ON DELETE NO ACTION ON UPDATE NO ACTION;
--
-- Constraints for table `staff`
--
ALTER TABLE `staff`
ADD CONSTRAINT `fk_staff_designation1` FOREIGN KEY (`designation_id_designation`) REFERENCES `designation` (`id_designation`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `fk_staff_status1` FOREIGN KEY (`status_id_status`) REFERENCES `status` (`id_status`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `fk_staff_title` FOREIGN KEY (`title_id_title`) REFERENCES `title` (`id_title`) ON DELETE NO ACTION ON UPDATE NO ACTION;
--
-- Constraints for table `staff_leave_application`
--
ALTER TABLE `staff_leave_application`
ADD CONSTRAINT `fk_staff_leave_leave_type1` FOREIGN KEY (`leave_type_id_leave_type`) REFERENCES `leave_type` (`id_leave_type`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `fk_staff_leave_staff1` FOREIGN KEY (`staff_id_staff`) REFERENCES `staff` (`id_staff`) ON DELETE CASCADE ON UPDATE NO ACTION;
Updated Trigger
BEGIN
set #loopcounter := 0;
set #counter:= -1;
set #balance:= (SELECT new_balance FROM leave_balance_view WHERE staff_id_staff = new.staff_id_staff and leave_type_id_leave_type = new.leave_type_id_leave_type);
-- set #newrows:= (select count(*) from tn_air_staff_leave_application);
WHILE ((#counter < DATEDIFF(DATE(new.end_date), DATE(new.start_date))) && (#loopcounter < #balance)) DO
INSERT INTO `leave`(staff_leave_application_id_staff_leave_application, staff_leave_application_staff_id_staff, leave_type_id_leave_type, date, active, date_updated)
VALUES (new.id_staff_leave_application, new.staff_id_staff, new.leave_type_id_leave_type, DATE_ADD(new.start_date, INTERVAL #counter:=#counter + 1 DAY), 1, CURDATE());
set #loopcounter := #loopcounter + 1;
END WHILE;
set #counter:=+(#balance - 1);
set #loopcounter:=0;
WHILE ((#counter < DATEDIFF(DATE(new.end_date), DATE(new.start_date))) && (#loopcounter < 2)) DO
INSERT INTO `nonpay_leave`(staff_leave_application_id_staff_leave_application, staff_leave_application_staff_id_staff, leave_type_id_leave_type, date, active, date_updated)
VALUES (new.id_staff_leave_application, new.staff_id_staff, new.leave_type_id_leave_type, DATE_ADD(new.start_date, INTERVAL #counter:=#counter + 1 DAY), 1, CURDATE());
end while;
END$$
set #loopcounter := 0;
set #counter:= -1;
WHILE ((#counter < DATEDIFF(DATE(new.end_date), DATE(new.start_date))) && (#loopcounter <5)) DO
INSERT INTO `leave`(staff_leave_application_id_staff_leave_application, staff_leave_application_staff_id_staff, leave_type_id_leave_type, date, active, date_updated)
VALUES (new.id_staff_leave_application, new.staff_id_staff, new.leave_type_id_leave_type, DATE_ADD(new.start_date, INTERVAL #counter:=#counter + 1 DAY), 1, CURDATE());
set #loopcounter := #loopcounter + 1;
END WHILE;
set #counter:=+4 (basically adjusting for the previous 5 that u marked in)
set #loopcounter:=0;
WHILE ((#counter < DATEDIFF(DATE(new.end_date), DATE(new.start_date))) && (#loopcounter <2)) DO
insert into NO_PAY_LEAVE
* the idea is a new loop_counter which goes to 5 before it breaks out of first loop.
* a new 2nd loop_counter which breaks at 2 or more (not sure wht the requirement is, maybe u wont need it in the 2nd loop)
* ur original counter adjusted to either +4 in the 2nd loop (not sure which one, sorta confused but i think it shud be +4 or it cud be
-6)
Ok i have edited and think this is what the new logic shud b.. many counters have changed
well alrite i get u, now u will have to do what u said.. before u enter any loop.. loop1 (max times it can execute is #balance times).. loop2 (it shud compulsarily execute the remainder times).. i think u shud set a new counter called leave_counter in the beginning itself which will determine how many times the Leave Loop will execute..
BEGIN
set #loopcounter := 0;
set #counter:= -1;
set #balance:= (SELECT new_balance FROM leave_balance_view WHERE staff_id_staff = new.staff_id_staff and leave_type_id_leave_type = new.leave_type_id_leave_type);
set #leavecounter:=+(#balance - 1);
-- set #newrows:= (select count(*) from tn_air_staff_leave_application);
WHILE ((#counter < DATEDIFF(DATE(new.end_date), DATE(new.start_date))) && (#loopcounter < #balance) && (#balance>0)) DO
INSERT INTO `leave`(staff_leave_application_id_staff_leave_application, staff_leave_application_staff_id_staff, leave_type_id_leave_type, date, active, date_updated)
VALUES (new.id_staff_leave_application, new.staff_id_staff, new.leave_type_id_leave_type, DATE_ADD(new.start_date, INTERVAL #counter:=#counter + 1 DAY), 1, CURDATE());
set #loopcounter := #loopcounter + 1;
set #balance := #balance - 1;
END WHILE;
WHILE ((#leavecounter < DATEDIFF(DATE(new.end_date), DATE(new.start_date)))) DO
INSERT INTO `nonpay_leave`(staff_leave_application_id_staff_leave_application, staff_leave_application_staff_id_staff, leave_type_id_leave_type, date, active, date_updated)
VALUES (new.id_staff_leave_application, new.staff_id_staff, new.leave_type_id_leave_type, DATE_ADD(new.start_date, INTERVAL #leavecounter:=#leavecounter + 1 DAY), 1, CURDATE());
end while;
END$$
BOTTOMLINE::::::
i have edited ur sql command by introducing a new counter called leave_counter which will determine how many times ur leave_loop shud run.. also in the first loop i have made sure that it does not execute more than #balance times by introducing the #balance in the first loop.. u can see the edited reply.. Loop 1: Executes max (#balance) times... Loop 2: Executes (no of days leave taken) - (#balance) times ...

mysql trigger - update value, value= row count

I want to run a mysql trigger to update value of table leave_taken col num, when a table called leave was updated, inserted or deleted.
Like if I insert this rows to leave:
INSERT INTO `leave` (`id_leave`, `staff_leave_application_id_staff_leave_application`, `staff_leave_application_staff_id_staff`, `leave_type_id_leave_type`, `date`, `active`, `date_updated`) VALUES
(7, 7, 6, 7, '2013-01-21', 1, '2013-01-18'),
(8, 7, 6, 7, '2013-01-22', 1, '2013-01-18'),
(9, 7, 6, 7, '2013-01-23', 1, '2013-01-18'),
(10, 7, 6, 7, '2013-01-24', 1, '2013-01-18'),
(11, 7, 6, 7, '2013-01-25', 2, '2013-01-18');
then table leave_taken col num value was updated to 5 where:
staff_leave_application_staff_id_staff = currently updated staff_leave_application_staff_id_staff,
and
leave_type_id_leave_type = currently updated leave_type_id_leave_type
I have included the Table below.
Table Leave
CREATE TABLE IF NOT EXISTS `leave` (
`id_leave` int(11) NOT NULL AUTO_INCREMENT,
`staff_leave_application_id_staff_leave_application` int(11) NOT NULL,
`staff_leave_application_staff_id_staff` int(11) NOT NULL,
`leave_type_id_leave_type` int(11) NOT NULL,
`date` date NOT NULL,
`active` int(11) NOT NULL DEFAULT '1',
`date_updated` date NOT NULL,
PRIMARY KEY (`id_leave`,`staff_leave_application_id_staff_leave_application`,`staff_leave_application_staff_id_staff`),
KEY `fk_table1_leave_type1` (`leave_type_id_leave_type`),
KEY `fk_table1_staff_leave_application1` (`staff_leave_application_id_staff_leave_application`,`staff_leave_application_staff_id_staff`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=12 ;
Table Leave taken:
CREATE TABLE IF NOT EXISTS `leave_balance` (
`id_leave_balance` int(11) NOT NULL AUTO_INCREMENT,
`staff_id_staff` int(11) NOT NULL,
`leave_type_id_leave_type` int(11) NOT NULL,
`balance` int(3) NOT NULL,
`date_added` date NOT NULL,
PRIMARY KEY (`id_leave_balance`),
UNIQUE KEY `id_leave_balance_UNIQUE` (`id_leave_balance`),
KEY `fk_leave_balance_staff1` (`staff_id_staff`),
KEY `fk_leave_balance_leave_type1` (`leave_type_id_leave_type`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
First, define a unique key over the identifying columns in your leave table:
ALTER TABLE leave
ADD UNIQUE (staff_leave_application_staff_id_staff, leave_type_id_leave_type);
Then go ahead and define your triggers:
CREATE TRIGGER my_insert_trigger AFTER INSERT ON leave FOR EACH ROW
INSERT INTO leave_taken
(staff_leave_application_staff_id_staff, leave_type_id_leave_type, num)
VALUES
(NEW.staff_leave_application_staff_id_staff, NEW.leave_type_id_leave_type, 1)
ON DUPLICATE KEY UPDATE
num = num + 1;
CREATE TRIGGER my_delete_trigger AFTER DELETE ON leave FOR EACH ROW
UPDATE leave_taken
SET num = num - 1
WHERE staff_leave_application_staff_id_staff = OLD.staff_leave_application_staff_id_staff
AND leave_type_id_leave_type = OLD.leave_type_id_leave_type;
DELIMITER ;;
CREATE TRIGGER my_update_trigger AFTER UPDATE ON leave FOR EACH ROW
IF NOT (
NEW.staff_leave_application_staff_id_staff <=> OLD.staff_leave_application_staff_id_staff
AND NEW.leave_type_id_leave_type <=> OLD.leave_type_id_leave_type
) THEN
UPDATE leave_taken
SET num = num - 1
WHERE staff_leave_application_staff_id_staff = OLD.staff_leave_application_staff_id_staff
AND leave_type_id_leave_type = OLD.leave_type_id_leave_type;
INSERT INTO leave_taken
(staff_leave_application_staff_id_staff, leave_type_id_leave_type, num)
VALUES
(NEW.staff_leave_application_staff_id_staff, NEW.leave_type_id_leave_type, 1)
ON DUPLICATE KEY UPDATE
num = num + 1;
END IF;;
DELIMITER ;