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

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")

Related

INSERT ON DUPLICATE KEY with INNER JOIN

Given t.id, a.id, t1.name and t2.name, how do I add or update t1_has_t2.data?
I can update it if there is currently a record.
UPDATE t1_has_t2
INNER JOIN t1 ON t1.id=t1_has_t2.t1_id
INNER JOIN t2 ON t2.id=t1_has_t2.t2_id
SET t1_has_t2.data=123
WHERE t1.name="foo" AND t1.t_id=333 AND t2.name="bar" AND t2.t_id=333;
How can I insert it if a record currently doesn't exist?
EDIT. Would it be something like the following? Seems a waste to include t in the JOIN.
INSERT INTO t1_has_t2(t1_id,t2_id,data)
SELECT t1.id, t2.id, 123
FROM t
INNER JOIN t1 ON t1.t_id=t.id
INNER JOIN t2 ON t2.t_id=t.id
WHERE t1.name="foo" AND t1.t_id=333 AND t2.name="bar" AND t2.t_id=333
ON DUPLICATE KEY SET t1_has_t2.data=123;
EDIT2. Ah, maybe I get it now. I just JOIN t1 and t2 to each other through their shared t.id?
INSERT INTO t1_has_t2(t1_id,t2_id,data)
SELECT t1.id, t2.id, 123
FROM t1
INNER JOIN t2 ON t2.t_id=t1.t_id
WHERE t1.name="foo" AND t1.t_id=333 AND t2.name="bar" AND t2.t_id=333
ON DUPLICATE KEY UPDATE t1_has_t2.data=123;
-- MySQL Script generated by MySQL Workbench
-- 08/08/16 07:40:04
-- Model: New Model Version: 1.0
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';
-- -----------------------------------------------------
-- Schema mydb
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `mydb` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ;
USE `mydb` ;
-- -----------------------------------------------------
-- Table `mydb`.`accounts`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`accounts` (
`id` INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `mydb`.`t`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`t` (
`id` INT NOT NULL AUTO_INCREMENT,
`accounts_id` INT NOT NULL,
PRIMARY KEY (`id`, `accounts_id`),
INDEX `fk_t_accounts_idx` (`accounts_id` ASC),
CONSTRAINT `fk_t_accounts`
FOREIGN KEY (`accounts_id`)
REFERENCES `mydb`.`accounts` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `mydb`.`t1`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`t1` (
`id` INT NOT NULL AUTO_INCREMENT,
`t_id` INT NOT NULL,
`t_accounts_id` INT NOT NULL,
`name` VARCHAR(45) NULL,
PRIMARY KEY (`id`),
INDEX `fk_t1_t1_idx` (`t_id` ASC, `t_accounts_id` ASC),
UNIQUE INDEX `un1` (`t_id` ASC, `name` ASC),
CONSTRAINT `fk_t1_t1`
FOREIGN KEY (`t_id` , `t_accounts_id`)
REFERENCES `mydb`.`t` (`id` , `accounts_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `mydb`.`t2`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`t2` (
`id` INT NOT NULL AUTO_INCREMENT,
`t_id` INT NOT NULL,
`t_accounts_id` INT NOT NULL,
`name` VARCHAR(45) NULL,
PRIMARY KEY (`id`),
INDEX `fk_t2_t1_idx` (`t_id` ASC, `t_accounts_id` ASC),
UNIQUE INDEX `un2` (`t_id` ASC, `name` ASC),
CONSTRAINT `fk_t2_t1`
FOREIGN KEY (`t_id` , `t_accounts_id`)
REFERENCES `mydb`.`t` (`id` , `accounts_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `mydb`.`t1_has_t2`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`t1_has_t2` (
`t1_id` INT NOT NULL,
`t2_id` INT NOT NULL,
`data` VARCHAR(45) NULL,
PRIMARY KEY (`t1_id`, `t2_id`),
INDEX `fk_t1_has_t2_t21_idx` (`t2_id` ASC),
INDEX `fk_t1_has_t2_t11_idx` (`t1_id` ASC),
CONSTRAINT `fk_t1_has_t2_t11`
FOREIGN KEY (`t1_id`)
REFERENCES `mydb`.`t1` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_t1_has_t2_t21`
FOREIGN KEY (`t2_id`)
REFERENCES `mydb`.`t2` (`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;
Works fine if I understand what you want with Insert on Duplicate Key Update (IODKU).
Data Load:
insert accounts(id) values (NULL); -- id = 1
insert t(accounts_id) values (1); -- id = 1
insert t1(t_id,t_accounts_id,name) values (1,1,'n1'); -- id=1
insert t1(t_id,t_accounts_id,name) values (1,1,'n2'); -- id=2
insert t2(t_id,t_accounts_id,name) values (1,1,'n1'); -- id=1
insert t2(t_id,t_accounts_id,name) values (1,1,'n2'); -- id=2
insert t1_has_t2(t1_id,t2_id,data) values(1,1,'one_one'); -- success
insert t1_has_t2(t1_id,t2_id,data) values(1,77,'x'); -- Error 1452 as expected
insert t1_has_t2(t1_id,t2_id,data) values(77,1,'x'); -- Error 1452 as expected
insert t1_has_t2(t1_id,t2_id,data) values(1,2,'one_two'); -- success
insert t1_has_t2(t1_id,t2_id,data) values(2,1,'two_one'); -- success
insert t1_has_t2(t1_id,t2_id,data) values(2,2,'two_two'); -- success
Your Query:
UPDATE t1_has_t2
INNER JOIN t1 ON t1.id=t1_has_t2.t1_id
INNER JOIN t2 ON t2.id=t1_has_t2.t2_id
SET t1_has_t2.data='I am a string'
WHERE t1.name="n1" AND t1.t_id=1 AND t2.name="n1" AND t2.t_id=1;
IODKU:
insert t1_has_t2(t1_id,t2_id,data) values(2,2,'two_two_version002')
on duplicate key update data='anchovies';
See results:
select * from t1_has_t2;
+-------+-------+---------------+
| t1_id | t2_id | data |
+-------+-------+---------------+
| 1 | 1 | I am a string |
| 1 | 2 | one_two |
| 2 | 1 | two_one |
| 2 | 2 | anchovies |
+-------+-------+---------------+
You can also look into
insert ignore t1_has_t2(t1_id,t2_id,data) [something];
Which succeeds or fails silently by design.

Mysql - The trigger do not update my database

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.

groups and sub-group up to 5 level database structure

i was wondering what is the best structure for a table in mysql,
The structure needs to have:
Parent (level 0)
-region (inside regions are)(level 1)
-countrys (inside countrys are)(level 2)
-Districts (level 3)
So I need to store all that info but in the same table, any clues??
If you need to know i building this app on cakephp.
Thanks in advance.
I've impulsively made an EER diagram for your situation.
Please tell me if it works (and if you agree), I'll be awaiting your feedback.
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 `hierarchy` ;
CREATE SCHEMA IF NOT EXISTS `hierarchy` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ;
USE `hierarchy` ;
-- -----------------------------------------------------
-- Table `hierarchy`.`level`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `hierarchy`.`level` (
`id` TINYINT UNSIGNED NOT NULL AUTO_INCREMENT ,
`name` VARCHAR(20) NOT NULL ,
PRIMARY KEY (`id`) ,
UNIQUE INDEX `name_UNIQUE` (`name` ASC) )
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `hierarchy`.`location`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `hierarchy`.`location` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`parent` INT UNSIGNED NULL ,
`name` VARCHAR(50) NOT NULL ,
`level` TINYINT UNSIGNED NULL ,
PRIMARY KEY (`id`) ,
INDEX `fk_location_location_idx` (`parent` ASC) ,
INDEX `fk_location_level1_idx` (`level` ASC) ,
INDEX `index_name` (`name` ASC) ,
CONSTRAINT `fk_location_location`
FOREIGN KEY (`parent` )
REFERENCES `hierarchy`.`location` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_location_level1`
FOREIGN KEY (`level` )
REFERENCES `hierarchy`.`level` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
USE `hierarchy` ;
-- -----------------------------------------------------
-- Placeholder table for view `hierarchy`.`details_location`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `hierarchy`.`details_location` (`location_id` INT, `location_name` INT, `parent_id` INT, `level_id` INT, `level_name` INT, `children` INT);
-- -----------------------------------------------------
-- View `hierarchy`.`details_location`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `hierarchy`.`details_location`;
USE `hierarchy`;
CREATE OR REPLACE VIEW `hierarchy`.`details_location` AS
SELECT
x.`id` AS `location_id`,
x.`name` AS `location_name`,
IFNULL(x.`parent`, 0) AS `parent_id`,
y.`id` AS `level_id`,
y.`name` AS `level_name`,
(SELECT COUNT(*) FROM location AS l WHERE l.parent = x.id) AS `children`
FROM location AS `x`
INNER JOIN `level` AS `y`
ON (x.`level` = y.id);
USE `hierarchy`;
DELIMITER $$
USE `hierarchy`$$
CREATE TRIGGER `insert_location` BEFORE INSERT ON location
FOR EACH ROW BEGIN
DECLARE x INT UNSIGNED DEFAULT 1;
IF NEW.parent IS NOT NULL THEN
SELECT `level`+1 INTO x FROM location WHERE id = NEW.parent;
END IF;
SET NEW.`level` = x;
END$$
DELIMITER ;
SET SQL_MODE=#OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=#OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=#OLD_UNIQUE_CHECKS;
-- -----------------------------------------------------
-- Data for table `hierarchy`.`level`
-- -----------------------------------------------------
START TRANSACTION;
USE `hierarchy`;
INSERT INTO `hierarchy`.`level` (`id`, `name`) VALUES (1, 'parent');
INSERT INTO `hierarchy`.`level` (`id`, `name`) VALUES (2, 'region');
INSERT INTO `hierarchy`.`level` (`id`, `name`) VALUES (3, 'country');
INSERT INTO `hierarchy`.`level` (`id`, `name`) VALUES (4, 'district');
COMMIT;
INSERT INTO location (parent,name,level) VALUES
(NULL,'a1',NULL), (NULL,'a2',NULL), (NULL,'a3',NULL);
INSERT INTO location (parent,name,level) VALUES
(1,'b1',NULL), (1,'b2',NULL), (2,'b3',NULL),
(2,'b4',NULL), (3,'b5',NULL), (3,'b6',NULL);
INSERT INTO location (parent,name,level) VALUES
(4,'c1',NULL), (4,'c2',NULL), (5,'c3',NULL),
(5,'c4',NULL), (6,'c5',NULL), (6,'c6',NULL),
(7,'c7',NULL), (7,'c8',NULL), (8,'c9',NULL),
(8,'c10',NULL), (9,'c11',NULL), (9,'c12',NULL);
SELECT * FROM details_location;
[(Mostly) auto-generated code from MySQL Workbench 5.2]
Note that the trigger insert_location determines item's level at registration time, increasing so the parent's level by one unit.

How to Add integer column to an String column in MySQl 5.0

I Want to add an Integer Column to a String that's because i need to generate a varchar variable with a numeric part that automatically increments. For example, P000001,P000002...
In order to do that what i am doing while creation of table i have taken an int field ID which auto_increments and i am Concatenating P with 00000 and the ID value
The Table i have created is :
CREATE TABLE tblAcceptTest(
ID int AUTO_INCREMENT NOT NULL primary key,
PatientID as CONCAT('P' , CONCAT('000000',CAST(ID as char)))
);
It Shows me the error from as keyword.
Please help
MySQL's documentation (http://dev.mysql.com/doc/refman/5.1/en/create-table.html) says, "the default value must be a constant; it cannot be a function or an expression." Why don't you just get the PatientID value afterward as part of the SELECT:
SELECT CONCAT('P', LPAD(ID, 6, 0)) AS PatientID FROM tblAcceptTest;
It looks like you want six digits after the "P", so try this for your expression:
CONCAT('P', LPAD(ID, 6, '0'))
Mysql has little support for computed columns.
Patient ID from your specification could be a char(7)
CREATE TABLE tblAcceptTest(
ID int AUTO_INCREMENT NOT NULL primary key,
PatientID char(7)
);
Then create some triggers. Note that the following insert trigger will cause issues with high concurrency servers.
DELIMITER |
CREATE TRIGGER tblAcceptTest_insert BEFORE INSERT ON tblAcceptTest
FOR EACH ROW BEGIN
DECLARE next_id INT;
SET next_id = (SELECT AUTO_INCREMENT FROM information_schema.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='tblAcceptTest');
SET NEW.PatientID = CONCAT('P' , RIGHT(CONCAT('000000',next_id),6)) ;
END;
|
CREATE TRIGGER tblAcceptTest_update BEFORE UPDATE ON tblAcceptTest
FOR EACH ROW BEGIN
SET NEW.PatientID = CONCAT('P' , RIGHT(CONCAT('000000',NEW.ID),6)) ;
END;
|
DELIMITER ;
You use relationships and views to achieve the same result.
CREATE TABLE `patient` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`patient` varchar(60) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `accepted_test` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`patient_id` int(11) NOT NULL,
`accepted` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `patient_id` (`patient_id`),
CONSTRAINT `accepted_test_ibfk_1` FOREIGN KEY (`patient_id`) REFERENCES `patient` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
create or replace view accepted_test_veiw as
select CONCAT('P' , RIGHT(CONCAT('000000',patient_id),6)) patient_key
, accepted
, id accepted_test_id
, patient_id
from accepted_test ;
select * from `accepted_test_veiw`

Dependency objects MySQL

Advise the GUI tool for viewing dependent object database MySQL.
for example:
USE db;
CREATE TABLE t1(
id INT(11) NOT NULL,
`column` INT(11) DEFAULT NULL,
UNIQUE INDEX id (id)
);
CREATE TABLE t2(
id INT(11) NOT NULL,
`column` INT(11) DEFAULT NULL,
INDEX FK_t2_t1_id (`column`),
CONSTRAINT FK_t2_t1_id FOREIGN KEY (`column`)
REFERENCES t1 (id) ON DELETE RESTRICT ON UPDATE RESTRICT
);
CREATE TABLE t3(
id INT(11) NOT NULL,
`column` INT(11) DEFAULT NULL,
INDEX FK_t3_t1_id (`column`),
CONSTRAINT FK_t3_t1_id FOREIGN KEY (`column`)
REFERENCES t1 (id) ON DELETE RESTRICT ON UPDATE RESTRICT
);
DELIMITER $$
CREATE DEFINER = 'root'#'localhost'
PROCEDURE procedure1()
BEGIN
SELECT
*
FROM
db.t1;
END
$$
DELIMITER ;
I want to see which objects refer to the table t1.
In this example it are t2, t3 and procedure1
This is most likely what you are looking for. The information can be found in information_schema.
SELECT pk.constraint_schema AS PKDatabaseName
, pk.table_name AS PKObjectName
, fk_cols.column_name AS PKColumnName
, fk_cols.referenced_table_schema AS FKDatabaseName
, fk_cols.referenced_table_name AS FKObjectName
, fk_cols.referenced_column_name AS FKColumnName
, pk.constraint_name AS ConstraintName
, fk_cols.ordinal_position AS ColumnIdx
FROM information_schema.table_constraints pk
INNER JOIN information_schema.key_column_usage fk_cols
ON pk.constraint_schema = fk_cols.table_schema
AND pk.table_name = fk_cols.table_name
AND pk.constraint_name = fk_cols.constraint_name
WHERE pk.constraint_type = 'FOREIGN KEY'
Your question isn't all that clear, but it sounds like you're looking for some sort of GUI tool to do data modeling with MySQL. If that's correct, try looking at MySQL Workbench.