Mysql - The trigger do not update my database - mysql

this is my trigger :
--
-- Déclencheurs `reservation`
--
DROP TRIGGER IF EXISTS `UpdateFactureOnInsert`;
DELIMITER //
CREATE TRIGGER `UpdateFactureOnInsert` AFTER INSERT ON `reservation`
FOR EACH ROW BEGIN
DECLARE quota, montant, tarif INT;
DECLARE nombreHeure INT DEFAULT (SELECT COUNT(heure.numero) FROM heure WHERE heure.code = NEW.code);
DECLARE mois INT DEFAULT (SELECT heure.mois FROM heure WHERE heure.code = NEW.code LIMIT 1);
DECLARE annee INT DEFAULT (SELECT heure.annee FROM heure WHERE heure.code = NEW.code LIMIT 1);
DECLARE identifiant INT DEFAULT (SELECT facture.identifiant FROM facture WHERE facture.association = NEW.association
AND facture.mois = mois
AND facture.annee = annee LIMIT 1);
IF (identifiant = null) THEN
SET identifiant = ((SELECT MAX(facture.identifiant) FROM facture) +1);
INSERT INTO facture (facture.association, facture.annee, facture.mois, facture.identifiant, facture.quota, facture.montant)
VALUES (NEW.association, annee, mois, identifiant, 20, 0);
END IF;
SET quota = (SELECT facture.quota FROM facture WHERE facture.identifiant = identifiant
AND facture.association = NEW.association
AND facture.mois = mois
AND facture.annee = annee);
SET montant = (SELECT facture.montant FROM facture WHERE facture.identifiant = identifiant
AND facture.association = NEW.association
AND facture.mois = mois
AND facture.annee = annee);
IF (nombreHeure >= quota) THEN
SET quota = quota - nombreHeure;
ELSE
SET tarif = (SELECT salle.tarif FROM salle WHERE salle.numero = NEW.numero);
SET montant = montant + (nombreHeure - quota) * tarif;
SET quota = 0;
END IF;
UPDATE facture SET facture.quota = quota, facture.montant = montant WHERE facture.association = NEW.association
AND facture.mois = mois
AND facture.annee = annee
AND facture.identifiant = identifiant;
END
//
DELIMITER ;
Those are my:
-- phpMyAdmin SQL Dump
-- version 4.0.4
-- http://www.phpmyadmin.net
--
-- Client: localhost
-- Généré le: Mer 02 Avril 2014 à 17:00
-- Version du serveur: 5.6.12-log
-- Version de PHP: 5.4.12
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET #OLD_CHARACTER_SET_CLIENT=##CHARACTER_SET_CLIENT */;
/*!40101 SET #OLD_CHARACTER_SET_RESULTS=##CHARACTER_SET_RESULTS */;
/*!40101 SET #OLD_COLLATION_CONNECTION=##COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Base de données: `reserv`
--
CREATE DATABASE IF NOT EXISTS `reserv` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
USE `reserv`;
-- --------------------------------------------------------
--
-- Structure de la table `association`
--
CREATE TABLE IF NOT EXISTS `association` (
`association` int(11) NOT NULL AUTO_INCREMENT,
`libelle` char(32) NOT NULL,
PRIMARY KEY (`association`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;
-- --------------------------------------------------------
--
-- Structure de la table `facture`
--
CREATE TABLE IF NOT EXISTS `facture` (
`association` int(11) NOT NULL,
`annee` int(11) NOT NULL,
`mois` int(11) NOT NULL,
`identifiant` int(11) NOT NULL,
`quota` int(11) NOT NULL,
`montant` int(11) NOT NULL,
PRIMARY KEY (`association`,`mois`,`annee`,`identifiant`),
KEY `i_fk_facture_mois` (`mois`,`annee`),
KEY `i_fk_facture_association` (`association`),
KEY `facture_ibfk_1` (`annee`,`mois`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Structure de la table `heure`
--
CREATE TABLE IF NOT EXISTS `heure` (
`numero` int(11) NOT NULL,
`association` int(11) NOT NULL,
`code` int(11) NOT NULL,
`annee` int(11) NOT NULL,
`mois` int(11) NOT NULL,
`jour` int(11) NOT NULL,
`heure` int(11) NOT NULL,
PRIMARY KEY (`numero`,`association`,`code`,`annee`,`mois`,`jour`,`heure`),
KEY `i_fk_heure_mois` (`annee`,`mois`),
KEY `i_fk_heure_reservation` (`numero`,`association`,`code`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Structure de la table `mois`
--
CREATE TABLE IF NOT EXISTS `mois` (
`mois` int(11) NOT NULL,
`annee` int(11) NOT NULL,
PRIMARY KEY (`annee`,`mois`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Structure de la table `reservation`
--
CREATE TABLE IF NOT EXISTS `reservation` (
`numero` int(11) NOT NULL,
`association` int(11) NOT NULL,
`code` int(11) NOT NULL,
PRIMARY KEY (`numero`,`association`,`code`),
KEY `i_fk_reservation_association` (`association`),
KEY `i_fk_reservation_salle` (`numero`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Structure de la table `salle`
--
CREATE TABLE IF NOT EXISTS `salle` (
`numero` int(11) NOT NULL AUTO_INCREMENT,
`capacite` int(11) NOT NULL,
`tarif` int(11) NOT NULL,
PRIMARY KEY (`numero`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
--
-- Contraintes pour les tables exportées
--
--
-- Contraintes pour la table `facture`
--
ALTER TABLE `facture`
ADD CONSTRAINT `facture_ibfk_1` FOREIGN KEY (`annee`, `mois`) REFERENCES `mois` (`annee`, `mois`),
ADD CONSTRAINT `facture_ibfk_2` FOREIGN KEY (`association`) REFERENCES `association` (`association`);
--
-- Contraintes pour la table `reservation`
--
ALTER TABLE `reservation`
ADD CONSTRAINT `reservation_ibfk_1` FOREIGN KEY (`association`) REFERENCES `association` (`association`),
ADD CONSTRAINT `reservation_ibfk_2` FOREIGN KEY (`numero`) REFERENCES `salle` (`numero`);
/*!40101 SET CHARACTER_SET_CLIENT=#OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=#OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=#OLD_COLLATION_CONNECTION */;
Just please tell me how can I fix it, because the trigger doesn't work properly.

One issue I see is that this conditional test:
IF (identifiant = null)
Will never return TRUE. If you want to test whether a variable is set to the NULL value, use the IS NULL operator.
IF (identifiant IS NULL)
I've never used a query as the DEFAULT value for a variable. (That may be valid, I've just never seen it done that way before.)
I'd code it like this:
DECLARE nombreHeure INT;
SELECT COUNT(heure.numero) INTO nombreHeure
FROM heure
WHERE heure.code = NEW.code;
Any place you are assigning the result from a query into a variable, you need to ensure that the query doesn't return more than one row. The query above will return a single row (assuming, that is, it doesn't throw an error), so it's okay.
For a lot of the other queries in your trigger it's not clear (to the casual reader) that these will return only one row.
Another big problem looks like you are local variables have the same name as columns in SQL statements. MySQL isn't going to see that as a reference to a variable, it's going to see it as a reference to a column. (When MySQL encounters a identifier in a SQL statement, it first checks to see if it's a column, only when it can't find a column of that name does it consider that it might be a variable.)
For example:
AND facture.mois = mois
For the reference to mois on the right side, MySQL first looks for a column named that in one of the tables (from any row source in scope), before it looks at it as a variable. In this case, it's going to find mois as a column in facture, so that SQL is basically equivalent to:
AND facture.mois = fracture.mois
which is effectively the same as:
AND facture.mois IS NOT NULL
Basically, you need to ensure that the variable names used in SELECT statements are distinct from all column names in tables referenced by the query.

Related

Update Column in Another Table Based off INT value Change using MySQL AFTER UPDATE Trigger

Getting error after error. Basically I am trying to set a columns value to 1 in my products table automatically if upon update of the product_stock table the column available is greater than 0 (meaning, at least one in stock).
MPN is both a unique and foreign key in my products table, so as long a positive value in the column available in the table product_stock the in_stock value for the mpn in the products table should be set to 1.
Two tables I'm working with:
1
CREATE TABLE `products` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`mpn` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`in_stock` int(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
UNIQUE KEY `mpn` (`mpn`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
2
CREATE TABLE `product_stock` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`mpn` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`size` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`available` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `product_stock_ibfk_1` (`mpn`),
CONSTRAINT `product_stock_ibfk_1` FOREIGN KEY (`mpn`) REFERENCES `products` (`mpn`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
And one variation of my trigger
DELIMITER $$
CREATE TRIGGER ps_update AFTER UPDATE ON `product_stock`
FOR EACH ROW BEGIN
IF NEW.available > 0 THEN
SET products.in_stock = 1;
ELSE
SET products.in_stock = 0;
END IF;
END$$
DELIMITER ;
Error code
1193 - Unknown system variable 'in_stock'
You cannot update value in another table using SET alone. You need to use proper UPDATE statement to do so.
I have also added more conditions, so that it does not fire UPDATE query every time. It will fire UPDATE only when there is a change in the in_stock value required.
DELIMITER $$
CREATE TRIGGER ps_update AFTER UPDATE ON `product_stock`
FOR EACH ROW BEGIN
-- update only when there is a change in the available
IF NEW.available <> OLD.available THEN
-- update only when item becomes in_stock
IF NEW.available > 0 AND OLD.available <= 0 THEN
UPDATE products
SET products.in_stock = 1
WHERE products.mpn = NEW.mpn;
-- update only when item becomes out_stock
ELSEIF NEW.available <= 0 AND OLD.available > 0 THEN
UPDATE products
SET products.in_stock = 0
WHERE products.mpn = NEW.mpn;
END IF;
END IF;
END $$
DELIMITER ;

Data Is not getting inserted in Mysql Database in a Node.js Real time notification app

I am trying to build a notification app which can notify changes in msql database using Nodejs and socket.io .
But mydata is not getting inserted in database. Attaching my db.js file and socketDemo.sql. My database name is socket.io
db.js file:-
var addComment = function(user,comment,mysql,pool,callback) {
console.log(user,comment);
var self = this;
pool.getConnection(function(err,connection){
if (err) {
//connection.release();
return callback(true,null);
} else {
var sqlQuery = "INSERT into UserComment (UserName,UserId,Comment) VALUES ((SELECT UserName FROM User WHERE UserName = user),id,comment)";
// var inserts =["UserComment","UserId","UserName",
// "Comment","UserId","User","UserName",
// user,user,comment];
//sqlQuery = mysql.format(sqlQuery,inserts);
connection.query(sqlQuery,function(err,rows){
connection.release();
if (err) {
return callback(true,null);
} else {
callback(false,"comment added");
}
});
}
connection.on('error', function(err) {
return callback(true,null);
});
});
};
module.exports.addComment = addComment;
socketDemo.sql:-
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET #OLD_CHARACTER_SET_CLIENT=##CHARACTER_SET_CLIENT */;
/*!40101 SET #OLD_CHARACTER_SET_RESULTS=##CHARACTER_SET_RESULTS */;
/*!40101 SET #OLD_COLLATION_CONNECTION=##COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `socketDemo`
--
-- --------------------------------------------------------
--
-- Table structure for table `User`
--
CREATE TABLE IF NOT EXISTS `User` (
`UserId` int(11) NOT NULL,
`UserName` varchar(25) NOT NULL,
`Password` varchar(25) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;
--
-- Dumping data for table `User`
--
INSERT INTO `User` (`UserId`, `UserName`, `Password`) VALUES
(1, 'Harshit', 'Harshit');
-- --------------------------------------------------------
--
-- Table structure for table `UserComment`
--
CREATE TABLE IF NOT EXISTS `UserComment` (
`UserId` int(11) NOT NULL,
`UserName` varchar(11) NOT NULL,
`Comment` text NOT NULL,
`PostId` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `UserComment`
--
INSERT INTO `UserComment` (`UserId`, `UserName`, `Comment`, `PostId`) VALUES
(1, 'Harshit', '\n \n \n \n \n ', 0);
-- --------------------------------------------------------
--
-- Table structure for table `UserPost`
--
CREATE TABLE IF NOT EXISTS `UserPost` (
`UserPostId` int(11) NOT NULL,
`UserPostContent` text NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;
--
-- Dumping data for table `UserPost`
--
INSERT INTO `UserPost` (`UserPostId`, `UserPostContent`) VALUES
(1, 'This is test comment.');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `User`
--
ALTER TABLE `User`
ADD PRIMARY KEY (`UserName`),
ADD KEY `UserIdIndex` (`UserId`);
--
-- Indexes for table `UserComment`
--
ALTER TABLE `UserComment`
ADD KEY `UserIdIndexComment` (`UserId`),
ADD KEY `PostIdIndex` (`PostId`);
--
-- Indexes for table `UserPost`
--
ALTER TABLE `UserPost`
ADD PRIMARY KEY (`UserPostId`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `User`
--
ALTER TABLE `User`
MODIFY `UserId` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=2;
--
-- AUTO_INCREMENT for table `UserPost`
--
ALTER TABLE `UserPost`
MODIFY `UserPostId` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=2;
/*!40101 SET CHARACTER_SET_CLIENT=#OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=#OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=#OLD_COLLATION_CONNECTION */;
Database schema:-
enter image description here
please help.
My first question is why do you want to use SELECT UserName FROM User WHERE UserName = user - you can simply use the user variable instead the SELECT statement.
What is more, if you are performing such a query and you want to use variables passed to the function, you need to pass them to the .query method:
connection.query("INSERT into UserComment (UserName,UserId,Comment) VALUES (?, ?, ?)", [user, id, comment], function(error, results){
// check error and perform further operations...
});
The [user, id, comment] part is used to replace the ? marks in the SQL query (remember to maintain order of those variables in the array).

How to get one column from 2 different tables

I have 2 tables in MySQL registerSMSusers and GroupsSMS. Both the tables have a column named as mobile. From an HTML form I am getting comma separated values like test,alltest,john. These comma separated values will be present in either of the 2 tables. For example test (name column) is present in registerSMSusers and alltest is present in GroupsSMS (GroupName column).
In Java I can split with comma and then check if its present in any of the tables or not.If present then get the mobile. Just wanted to know are there any SQL queries for the same.
This is SQL schema
DROP TABLE IF EXISTS `GroupsSMS`;
/*!40101 SET #saved_cs_client = ##character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `GroupsSMS` (
`Name` varchar(50) DEFAULT NULL,
`email` varchar(50) DEFAULT NULL,
`mobile` varchar(20) DEFAULT NULL,
`GroupName` varchar(20) DEFAULT NULL,
`GroupID` int(11) NOT NULL AUTO_INCREMENT,
`dataselected` varchar(50) DEFAULT NULL,
PRIMARY KEY (`GroupID`)
) ENGINE=MyISAM AUTO_INCREMENT=191 DEFAULT CHARSET=latin1;
DROP TABLE IF EXISTS `registerSmsUsers`;
/*!40101 SET #saved_cs_client = ##character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `registerSmsUsers` (
`name` varchar(50) DEFAULT NULL,
`email` varchar(50) DEFAULT NULL,
`mobile` varchar(20) DEFAULT NULL,
`uid` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`uid`),
UNIQUE KEY `mobile` (`mobile`),
UNIQUE KEY `email` (`email`)
) ENGINE=MyISAM AUTO_INCREMENT=83 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = #saved_cs_client */;
And this is the sqlfiddle
I you have split the string in Java
String names[] = csv.split(',');
You can search for the corresponding mobile number in either registerSmsUsers or GroupsSMS with
PreparedStatement stmt = conn.prepareStatment("select u.mobile from registerSmsuser u where u.name = ? union select g.mobile from GroupsSMS g where g.groupname = ?");
stmt.setString(1, names[0]);
stmt.setString(2, names[0]);
ResultSet rs = stmt.executeQuery();
if (rs.first()) {
// do something with the mobile number
}
This will select entries from both the user and the groups table. If you need to know, where the number is from, you can add a fixed string to your select
select u.mobile, 'user' as origin from registerSmsuser u ...
union
select g.mobile, 'groups' as origin from GroupsSMS g ...
MySQL does not have a ready made function for splitting a CSV string. You have to do it manually using SUBSTRING using SUBSTRING_INDEX or using a REGEXP.
See details on a similar problem here
After you have say split the CSV into actual strings which are stored in a table 'CSVTable' {id, strvalue}, you can check like
SELECT G.mobile as mobilenumber
FROM 'GroupsSMS' G LEFT JOIN 'CSVTable' C
on G.GroupName =C.strvalue
WHERE C.strvalue is NOT NULL
UNION
SELECT R.mobile as mobilenumber
FROM 'registerSMSusers' R LEFT JOIN 'CSVTable' C
on R.name=C.strvalue
WHERE C.strvalue is NOT NULL
Note I have not used UNION ALL to get distinct set values
Pseudo code for getting values into temp table
DECLARE #CSVTABLE TABLE ( id int not null, strvalue NVARCHAR(400) NOT NULL)
DECLARE #var int
SET #var=1
DECLARE #STREXP NVARCHAR(MAX)
DECLARE #BUFF NVARHCAR(400)
SET #BUFF=SUBSTRING_INDEX(#STREXP,',',1)
SET #STREXP=REPLACE(#STREXp,#BUFF+',','')
WHILE #BUFF IS NOT NULL DO
INSERT INTO #temp VALUES(#var,#BUFF)
#var=#var+1
#VUFF
END WHILE

Generate auto incremented id for BPM application

Within a BPM web application, I have a field for an invoice # on a particular page but I need for it to be auto generated every time a user attaches an invoice and views that page. That number must be unique and preferably auto-incremented. A value for the invoice # field can be displayed by querying from a table from an external MYSQL database. So every time a user lands on that particular page, a SELECT query statement can be fired.
On MYSQL end, how would I set this up? So basically, I would like to setup a query for that invoice # field where it will for run a query for example,
SELECT invoice_num FROM invoice_generator
and every time this query runs, it would return the next incremented number.
You can use mysql trigger concept here....
I have added one example here...
It will be very usefull for u (see this link also :http://www.freemindsystems.com/mysql-triggers-a-practical-example/)
CREATE TABLE `products` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL DEFAULT '',
`price` int(20) NOT NULL DEFAULT '0',
`other` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `products_name_idx` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `freetags` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`tag` varchar(50) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `freetagged_objects` (
`tag_id` int(20) NOT NULL DEFAULT '0',
`object_id` int(20) NOT NULL DEFAULT '0',
`tagged_on` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`module` varchar(50) NOT NULL DEFAULT '',
PRIMARY KEY (`tag_id`, `object_id`),
KEY `freetagged_objects_tag_id_object_id_idx` (`tag_id`, `object_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
INSERT_PRODUCTS_TAGS
DELIMITER ||
DROP TRIGGER IF EXISTS insert_products_tags;
||
DELIMITER ##
CREATE TRIGGER insert_products_tags AFTER INSERT ON products
FOR EACH ROW
BEGIN
DECLARE current_id integer;
DECLARE tag_id integer;
DECLARE next integer;
DECLARE tag_field varchar(255);
DECLARE next_sep integer;
DECLARE current_tag varchar(255);
DECLARE right_tag varchar(255);
-- We use the field other as comma-separated tag_field
SET tag_field = NEW.other;
-- Check for empty tags
IF (CHAR_LENGTH(tag_field) <> 0) THEN
-- Loop until no more ocurrencies
set next = 1;
WHILE next = 1 DO
-- Find possition of the next ","
SELECT INSTR(tag_field, ',') INTO next_sep;
IF (next_sep > 0) THEN
SELECT SUBSTR(tag_field, 1, next_sep - 1) INTO current_tag;
SELECT SUBSTR(tag_field, next_sep + 1, CHAR_LENGTH(tag_field)) INTO right_tag;
set tag_field = right_tag;
ELSE
set next = 0;
set current_tag = tag_field;
END IF;
-- Drop spaces between comas
SELECT TRIM(current_tag) INTO current_tag;
-- Insert the tag if not already present
IF (NOT EXISTS (SELECT tag FROM freetags WHERE tag = current_tag)) THEN
-- Insert the tag
INSERT INTO freetags (tag) values (current_tag);
SELECT LAST_INSERT_ID() INTO tag_id;
ELSE
-- Or get the id
SELECT id FROM freetags WHERE tag = current_tag INTO tag_id;
END IF;
-- Link the object tagged with the tag
INSERT INTO freetagged_objects
(tag_id, object_id, module)
values
(tag_id, NEW.id, 'products');
END WHILE;
END IF;
END;
##
Now If you execute an insert on products table:
INSERT INTO PRODUCTS
(name, price, other)
values
("product1", 2, "tag1, tag2,tag3 , tag 4");

Error 1054: Column doesn't exist... it does?

Below are my table structures and foreign keys:
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';
CREATE SCHEMA IF NOT EXISTS `homework9` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci ;
USE `homework9` ;
-- -----------------------------------------------------
-- Table `homework9`.`employee`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `homework9`.`employee` ;
CREATE TABLE IF NOT EXISTS `homework9`.`employee` (
`EmployeeNumber` INT NOT NULL ,
`FirstName` VARCHAR(15) NULL ,
`LastName` VARCHAR(15) NULL ,
`Department` VARCHAR(15) NULL ,
`Phone` VARCHAR(15) NULL ,
`Email` VARCHAR(25) NULL ,
PRIMARY KEY (`EmployeeNumber`) )
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `homework9`.`computer`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `homework9`.`computer` ;
CREATE TABLE IF NOT EXISTS `homework9`.`computer` (
`SerialNumber` INT NOT NULL ,
`Make` VARCHAR(12) NOT NULL ,
`Model` VARCHAR(24) NOT NULL ,
`ProcessorType` VARCHAR(24) NULL ,
`ProcessorSpeed` DECIMAL(3,2) NOT NULL ,
`MainMemory` VARCHAR(15) NOT NULL ,
`DiskSize` VARCHAR(15) NOT NULL ,
PRIMARY KEY (`SerialNumber`) )
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `homework9`.`computer_assignment`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `homework9`.`computer_assignment` ;
CREATE TABLE IF NOT EXISTS `homework9`.`computer_assignment` (
`EmployeeNumber` INT NOT NULL ,
`SerialNumber` INT NOT NULL ,
`DateAssigned` DATETIME NOT NULL ,
`DateReassigned` DATETIME NULL ,
PRIMARY KEY (`EmployeeNumber`, `SerialNumber`) ,
INDEX `fk_computer_assignment_computer1` (`SerialNumber` ASC) ,
CONSTRAINT `fk_computer_assignment_employee`
FOREIGN KEY (`EmployeeNumber` )
REFERENCES `homework9`.`employee` (`EmployeeNumber` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_computer_assignment_computer1`
FOREIGN KEY (`SerialNumber` )
REFERENCES `homework9`.`computer` (`SerialNumber` )
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;
The updates I'm trying to run causing the error I have...
USE homework9;
set sql_safe_updates=0;
UPDATE employee SET Department = 'marketing' WHERE EmployeeNumber = 9;
UPDATE employee SET phone = '315-999-3344' WHERE LastName = 'rubble';
UPDATE computer SET make = 'Dell', model = 'OptiPlex 980', processortype = 'Intel i3-650',
processorspeed = 3.20, mainmemory = '4.0 GBytyes', DiskSize = '1.0 TBytes'
WHERE SerialNumber = 9871278;
UPDATE computer SET processorspeed = processorspeed + 0.50;
DELETE FROM computer_assignment WHERE EmployeeNumber = 11;
DELETE FROM employee WHERE EmployeeNumber = 11;
DELETE FROM computer_assignment WHERE computer_assignment.EmployeeNumber = employee.EmployeeNumber AND employee.LastName = 'rubble';
set sql_safe_updates=1;
select * from employee;
select * from computer;
select * from computer_assignment;
Result in this error: Unknown column employee.EmployeeNumber in where clause.
What's going on? Any help is greatly appreciated!
DELETE FROM computer_assignment
WHERE computer_assignment.EmployeeNumber = employee.EmployeeNumber
AND employee.LastName = 'rubble';
You haven't mentioned table employee in the FROM clause, so it's unknown.
Maybe you meant
DELETE FROM computer_assignment
WHERE computer_assignment.EmployeeNumber in
(select employee.EmployeeNumber from employee WHERE
employee.LastName = 'rubble')
DELETE FROM computer_assignment
WHERE computer_assignment.EmployeeNumber = employee.EmployeeNumber
AND employee.LastName = 'rubble'
The problem is that employee is not defined anywhere in this query.
DELETE FROM computer_assignment
INNER JOIN employee ON computer_assignment.EmployeeNumber = employee.EmployeeNumber
WHERE computer_assignment.EmployeeNumber = employee.EmployeeNumber
AND employee.LastName = 'rubble'
You're referencing only the computer_assignment table in the FROM so the employee table isn't available here.
DELETE FROM computer_assignment WHERE computer_assignment.EmployeeNumber = employee.EmployeeNumber AND employee.LastName = 'rubble';
Try this:
DELETE FROM computer_assignment WHERE computer_assignment.EmployeeNumber IN (SELECT EmployeeNumber FROM employee WHERE LastName = "Rubble")