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.
Related
My database >
CREATE TABLE `tblcompetition` (
`fldCompID` int(11) NOT NULL,
`fldDate` date NOT NULL,
`fldCompName` varchar(80) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dataark for tabell `tblcompetition`
--
INSERT INTO `tblcompetition` (`fldCompID`, `fldDate`, `fldCompName`) VALUES
(1, '2018-12-31', 'Winter Warmer'),
(2, '2019-01-31', 'Fresh New Year'),
(3, '2019-02-28', 'Month of Love'),
(4, '2018-11-30', 'Seaside Scenery');
-- --------------------------------------------------------
--
-- Tabellstruktur for tabell `tblimage`
--
CREATE TABLE `tblimage` (
`fldImageID` int(11) NOT NULL,
`fldMemberID` int(11) NOT NULL,
`fldCatID` int(11) NOT NULL,
`fldFilePath` varchar(256) NOT NULL,
`fldName` varchar(256) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dataark for tabell `tblimage`
--
INSERT INTO `tblimage` (`fldImageID`, `fldMemberID`, `fldCatID`, `fldFilePath`, `fldName`) VALUES
(6, 1, 6, 'images/Screen Shot 2019-02-14 at 14.42.07.png', 'Sunrise'),
(7, 1, 6, 'images/Screen Shot 2019-02-14 at 14.42.07.png', 'SunDown'),
(9, 11, 4, 'Imge1', 'Time Goes By'),
(18, 1, 1, 'images/Aloe.jpg', 'Aloe'),
(19, 1, 1, 'images/Aloe.jpg', 'Blur'),
(20, 1, 1, 'images/Aloe.jpg', 'Winter Time in the Country'),
(21, 1, 1, 'images/Aloe.jpg', 'Warmth'),
(22, 11, 4, 'he', 'Tomorrow');
-- --------------------------------------------------------
--
-- Tabellstruktur for tabell `tblmembentcomp`
--
CREATE TABLE `tblmembentcomp` (
`fldMembEntCompID` int(11) NOT NULL,
`fldCompID` int(11) NOT NULL,
`fldMemberID` int(11) NOT NULL,
`fldResult` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dataark for tabell `tblmembentcomp`
--
INSERT INTO `tblmembentcomp` (`fldMembEntCompID`, `fldCompID`, `fldMemberID`, `fldResult`) VALUES
(1, 2, 11, 11),
(2, 2, 1, 17),
(3, 2, 5, 19),
(4, 2, 3, 7),
(5, 2, 12, 4);
--
-- Indexes for dumped tables
--
--
-- Indexes for table `tblcompetition`
--
ALTER TABLE `tblcompetition`
ADD PRIMARY KEY (`fldCompID`);
--
-- Indexes for table `tblimage`
--
ALTER TABLE `tblimage`
ADD PRIMARY KEY (`fldImageID`),
ADD KEY `fldMemberID` (`fldMemberID`),
ADD KEY `fldCatID` (`fldCatID`);
--
-- Indexes for table `tblmembentcomp`
--
ALTER TABLE `tblmembentcomp`
ADD PRIMARY KEY (`fldMembEntCompID`),
ADD UNIQUE KEY `fldMemberID` (`fldMemberID`),
ADD KEY `fldCompID` (`fldCompID`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `tblcompetition`
--
ALTER TABLE `tblcompetition`
MODIFY `fldCompID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
--
-- AUTO_INCREMENT for table `tblimage`
--
ALTER TABLE `tblimage`
MODIFY `fldImageID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=23;
--
-- AUTO_INCREMENT for table `tblmembentcomp`
--
ALTER TABLE `tblmembentcomp`
MODIFY `fldMembEntCompID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
--
-- Begrensninger for dumpede tabeller
--
--
-- Begrensninger for tabell `tblimage`
--
ALTER TABLE `tblimage`
ADD CONSTRAINT `tblimage_ibfk_1` FOREIGN KEY (`fldMemberID`) REFERENCES `tblmember` (`fldMemberID`),
ADD CONSTRAINT `tblimage_ibfk_2` FOREIGN KEY (`fldCatID`) REFERENCES `tblcategory` (`fldCatID`);
--
-- Begrensninger for tabell `tblmembentcomp`
--
ALTER TABLE `tblmembentcomp`
ADD CONSTRAINT `tblmembentcomp_ibfk_1` FOREIGN KEY (`fldCompID`) REFERENCES `tblcompetition` (`fldCompID`),
ADD CONSTRAINT `tblmembentcomp_ibfk_2` FOREIGN KEY (`fldMemberID`) REFERENCES `tblmember` (`fldMemberID`);
when i do >
SELECT tblmembentcomp.fldCompID, tblmembentcomp.fldMemberID, tblmembentcomp.fldResult, tblimage.fldMemberID FROM tblmembentcomp JOIN tblcompetition ON tblmembentcomp.fldCompID=tblcompetition.fldCompID ORDER BY tblmembentcomp.fldResult DESC LIMIT 3
i get 19,17,11 thats correct , but when i add > JOIN tblimage ON tblmembentcomp.fldMemberID=tblimage.fldMemberID
or full search string>
SELECT tblmembentcomp.fldCompID, tblmembentcomp.fldMemberID, tblmembentcomp.fldResult, tblimage.fldMemberID FROM tblmembentcomp JOIN tblcompetition ON tblmembentcomp.fldCompID=tblcompetition.fldCompID JOIN tblimage ON tblmembentcomp.fldMemberID=tblimage.fldMemberID ORDER BY tblmembentcomp.fldResult DESC LIMIT 3
i only get 17,17,17
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
I have a MySQL DB that needs to provide attributes associated with a taxonomy. I desire to have a list of all attributes, including "inherited attributes" for a given element in the taxonomy. I'm not an SQL expert & have learned (and plagiarized) much from this site. One thing I learned here is to use a Closure Table to represent my Hierarchy. What I need to do for my database is associate a large number of attributes to elements within hierarchy. However, I can't seem to figure out how to grab all of the attributes associated with a given node and all of its parents. I created the following example database for the purpose of this question (feel free to comment on anything about this schema, the fake data is just noise).
My example MySQL database structure looks like this:
-- Simple Sample
SET FOREIGN_KEY_CHECKS=0;
DROP TRIGGER IF EXISTS inheritance_tree_insert;
DROP TRIGGER IF EXISTS inheritance_tree_update;
DROP TABLE IF EXISTS inheritance_paths;
DROP TABLE IF EXISTS inheritance_tree;
DROP TABLE IF EXISTS attributes;
SET FOREIGN_KEY_CHECKS=1;
CREATE TABLE `inheritance_tree` (
`it_id` INT NOT NULL, -- PK
`parent` INT, -- Parent id & FK
`child_order` INT, -- Oder of siblings
`name` VARCHAR(500) NOT NULL, -- Name for the entry
PRIMARY KEY (`it_id`),
FOREIGN KEY (`parent`) REFERENCES inheritance_tree(`it_id`) ON DELETE CASCADE,
INDEX(`name`)
) ENGINE = INNODB;
-- Trigger to update the paths table for new entries
DELIMITER //
CREATE TRIGGER `inheritance_tree_insert` AFTER INSERT ON `inheritance_tree` FOR EACH ROW
BEGIN
INSERT INTO `inheritance_paths` (`ancestor`, `descendant`, `len`)
SELECT `ancestor`, NEW.`it_id`, len + 1 FROM `inheritance_paths`
WHERE `descendant` = NEW.`parent`
UNION ALL SELECT NEW.`it_id`, NEW.`it_id`, 0;
END; //
DELIMITER ;
DELIMITER //
CREATE TRIGGER `inheritance_tree_update` BEFORE UPDATE ON `inheritance_tree` FOR EACH ROW
BEGIN
-- From http://www.mysqlperformanceblog.com/2011/02/14/moving-subtrees-in-closure-table/
IF OLD.`parent` != NEW.`parent` THEN
-- Remove the node from its current parent
DELETE a FROM `inheritance_paths` AS a
JOIN `inheritance_paths` AS d ON a.`descendant` = d.`descendant`
LEFT JOIN `inheritance_paths` AS x
ON x.`ancestor` = d.`ancestor` AND x.`descendant` = a.`ancestor`
WHERE d.`ancestor` = OLD.`it_id` AND x.`ancestor` IS NULL;
-- Add the node to its new parent
INSERT `inheritance_paths` (`ancestor`, `descendant`, `len`)
SELECT supertree.`ancestor`, subtree.`descendant`, supertree.`len`+subtree.`len`+1
FROM `inheritance_paths` AS supertree JOIN `inheritance_paths` AS subtree
WHERE subtree.`ancestor` = OLD.`it_id`
AND supertree.`descendant` = NEW.`parent`;
END IF;
END; //
DELIMITER ;
CREATE TABLE `inheritance_paths` (
`ancestor` INT NOT NULL,
`descendant` INT NOT NULL,
`len` INT NOT NULL,
PRIMARY KEY (`ancestor`, `descendant`),
FOREIGN KEY (`ancestor`) REFERENCES inheritance_tree(`it_id`) ON DELETE CASCADE,
FOREIGN KEY (`descendant`) REFERENCES inheritance_tree(`it_id`) ON DELETE CASCADE
) ENGINE = INNODB;
INSERT INTO `inheritance_tree` VALUES(1, NULL, NULL, 'Animal');
INSERT INTO `inheritance_tree` VALUES(2, 1, 1, 'Mammal');
INSERT INTO `inheritance_tree` VALUES(3, 1, 2, 'Bird');
INSERT INTO `inheritance_tree` VALUES(4, 1, 3, 'Reptile');
INSERT INTO `inheritance_tree` VALUES(5, 2, 2, 'Feline');
INSERT INTO `inheritance_tree` VALUES(6, 2, 1, 'Bovine');
INSERT INTO `inheritance_tree` VALUES(7, 1, 3, 'Fish');
INSERT INTO `inheritance_tree` VALUES(8, 4, 1, 'Snake');
INSERT INTO `inheritance_tree` VALUES(9, 4, 2, 'Lizard');
INSERT INTO `inheritance_tree` VALUES(10, NULL, NULL, 'Machine');
INSERT INTO `inheritance_tree` VALUES(11, 10, 1, 'Automobile');
INSERT INTO `inheritance_tree` VALUES(12, 10, 2, 'OfficeMachine');
INSERT INTO `inheritance_tree` VALUES(13, 10, 3, 'Robot');
DELIMITER ;
CREATE TABLE `attributes` (
`a_id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'the unique identifier',
`attribute_name` varchar(255) DEFAULT NULL,
`attribute_type` int(11) NOT NULL,
PRIMARY KEY (`a_id`),
KEY `fk_attributes_attribute_type1_idx` (`attribute_type`),
CONSTRAINT `fk_attributes_attribute_type1_idx` FOREIGN KEY (`attribute_type`) REFERENCES `inheritance_tree` (`it_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=latin1;
INSERT INTO `attributes` VALUES(1, 'IsAlive', 1); -- Animal
INSERT INTO `attributes` VALUES(2, 'HasMaximumLifeSpan', 1); -- Animal
INSERT INTO `attributes` VALUES(3, 'IsNotAlive', 10); -- Machine
INSERT INTO `attributes` VALUES(4, 'HasIndeterminantLifeSpan', 10); -- Machine
INSERT INTO `attributes` VALUES(5, 'BreathesAir', 2); -- Mammal
INSERT INTO `attributes` VALUES(6, 'CanFly', 3); -- Bird
INSERT INTO `attributes` VALUES(7, 'HasFeathers', 3); -- Bird
INSERT INTO `attributes` VALUES(8, 'ColdBlooded', 4); -- Reptile
INSERT INTO `attributes` VALUES(9, 'HasFourLegs', 5); -- Feline
INSERT INTO `attributes` VALUES(10, 'HasFourLegs', 6); -- Bovine
INSERT INTO `attributes` VALUES(11, 'ColdBlooded', 7); -- Fish
INSERT INTO `attributes` VALUES(12, 'HasNoLegs', 8); -- Snake
INSERT INTO `attributes` VALUES(13, 'HasFourLegs', 9); -- Lizard
INSERT INTO `attributes` VALUES(14, 'ConsumesGasoline', 11); -- Automobile
INSERT INTO `attributes` VALUES(15, 'ConsumesElectricity', 12); -- OfficeMachine
INSERT INTO `attributes` VALUES(16, 'ConsumesElectricity', 13); -- Robot
INSERT INTO `attributes` VALUES(17, 'WarmBlooded', 2); -- Mammal
INSERT INTO `attributes` VALUES(18, 'WarmBlooded', 3); -- Bird
INSERT INTO `attributes` VALUES(19, 'BreathesWater', 7); -- Fish
INSERT INTO `attributes` VALUES(20, 'HasScales', 8); -- Snake
INSERT INTO `attributes` VALUES(21, 'HasSkin', 9); -- Lizard
Assumptions:
1.All entities in the taxonomy are uniquely named. This means there is one and only one sub-type called “Fish” anywhere in any of the taxonomy trees.
2.Attributes are not unique and may repeat
GOAL:
Given the input type “Lizard” I would like a single query that returns the following list of attribute records:
1, IsAlive, 1
2, HasMaximumLifeSpan, 1
5, BreathesAir, 2
8, ColdBlooded, 4
13, HasFourLegs, 9
21, HasSkin, 9
SELECT a.*
FROM inheritance_tree t
JOIN inheritance_paths p ON p.descendant = t.it_id
JOIN attributes a ON a.attribute_type = p.ancestor
WHERE t.name = 'Lizard'
See it on sqlfiddle.
Note that your example output includes a_id = 5 (BreathesAir), which is a property of it_id = 2 (Mammal), which is not in the Lizard's ancestry.
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
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.