using foreign keys with mysql - mysql

I have a forgiven key issue using MySQL. I have a studies table and a samples table. Users can add studies and also add samples. every sample belongs to a study, but studies can have many samples. So theres a one to many relationship with studies and samples. I need to set up a foreign key in the samples table so that whenever a new sample is created it can be referenced by its parent study. I set up a foreign key in the sample table with this script below, but whenever I add a new sample it leaves the study_id column empty. I’m new using foreign keys so any examples would be great. Thanks.
CREATE TABLE `studies` (
`study_id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) DEFAULT NULL,
`study_name` varchar(45) DEFAULT NULL,
`description` tinytext,
`reads` varchar(45) DEFAULT NULL,
`created_at` varchar(45) DEFAULT NULL,
PRIMARY KEY (`study_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;
CREATE TABLE `samples` (
`sample_id` int(11) NOT NULL AUTO_INCREMENT,
`study_id` int(11) DEFAULT NULL,
`sample_name` varchar(45) DEFAULT NULL,
`created_at` varchar(45) DEFAULT NULL,
PRIMARY KEY (`sample_id`),
FOREIGN KEY (`study_id`)
REFERENCES `studies` (`study_id`)
ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;

Related

Should I use Inner Join in this case?

I am working on a student attendance mini-project, and I don't know how to proceed for my database. I'm new to SQL and databases in general so this might seem dumb to you.
So, I want to do a database containing the table student, which contains : student_id (primary key) , name (string) and attendance(boolean) (that's the bare minimum, i'll add more afterwards) and I want to register the daily attendance of the students. So I want to have all the students tied to every date of the week.
I created a date table in phpMyadmin but I don't know how to proceed to link them, i've tried an Inner Join and it was successful.
The problem is : If i want to add another line to the student table my table won't update, so is there a way to "automatically" tie all the students to the date table ?
Sorry if this seems confused I've tried my best to summarize it !
Lets have some idea about tables should be there to implement a proper Student Attendance system in place. I have copied create script for some of my tables that used for maintaining Students record per course. I hope following sample Table scripts with relation will help you understanding regarding table structure and also to solve your issue.
Please be noted, That this table structures for your your reference only. You can add/remove tables/columns as per your requirement once you get an overall idea from this post.
CREATE TABLE `staff` (
`id` int(11) NOT NULL,
`type` varchar(200) DEFAULT NULL,
`first_name` varchar(200) DEFAULT NULL,
`last_name` varchar(200) DEFAULT NULL,
`emal` varchar(200) DEFAULT NULL,
`contact` varchar(200) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `batch` (
`id` int(11) NOT NULL,
`department` varchar(200) DEFAULT NULL,
`details` varchar(200) DEFAULT NULL,
`staff_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `batch_staff_idx` (`staff_id`),
CONSTRAINT `batch_staff` FOREIGN KEY (`staff_id`) REFERENCES `staff` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `student` (
`id` int(11) NOT NULL,
`batch_id` int(11) DEFAULT NULL,
`first_name` varchar(200) DEFAULT NULL,
`last_name` varchar(200) DEFAULT NULL,
`email` varchar(200) DEFAULT NULL,
`contact` varchar(200) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `batch_student_idx` (`batch_id`),
CONSTRAINT `batch_student` FOREIGN KEY (`batch_id`) REFERENCES `batch` (`batch_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `course` (
`id` int(11) NOT NULL,
`name` varchar(200) DEFAULT NULL,
`details` varchar(200) DEFAULT NULL,
`staff_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `course_staff_idx` (`staff_id`),
CONSTRAINT `course_staff` FOREIGN KEY (`staff_id`) REFERENCES `staff` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `attendence` (
`course_id` int(11) NOT NULL,
`student_id` int(11) DEFAULT NULL,
`class_date` date DEFAULT NULL,
KEY `att_course_idx` (`course_id`),
KEY `att_student_idx` (`student_id`),
CONSTRAINT `att_course` FOREIGN KEY (`course_id`) REFERENCES `course` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `att_student` FOREIGN KEY (`student_id`) REFERENCES `student` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Your required data will finally store into table Attendance. From this table data, you will be able to find list of students absent/present per date and per course. Remember, the attendance table should enrich daily from a automated OR a manual process.

Interpretation of model diagram for allocation of foreign/primary keys

https://imgur.com/a/HAlSO7z
I am totally confused as to what I should identify as the primary key for the flatpack components table. For the flatpack components, there is a multiplicty relationship with both of the other tables, although intuitively I am leaning toward the component table because that seems more relevant, and the multiplicity is 0 to Many to 1, as opposed to the Many to 1 associated with flatpack components.
I have tried a composite key of both flatpackID and componentNo, but have ran into errors whilst trying to populate the table with sample data.
At present, I have the following tables:
CREATE TABLE `flatpack_apn` (
`flatpackid` INT(11) NOT NULL AUTO_INCREMENT,
`name` TINYTEXT NOT NULL,
`colour` TEXT NULL DEFAULT NULL,
`flatpacktype` ENUM('Office','Kitchen','Bedroom','General') NOT NULL,
`unitprice` DECIMAL(5,2) NULL DEFAULT NULL,
PRIMARY KEY (`flatpackid`)
)
COLLATE='hp8_english_ci'
ENGINE=InnoDB
AUTO_INCREMENT=2217
;
CREATE TABLE `component_apn` (
`componentno` INT(11) NOT NULL AUTO_INCREMENT,
`description` VARCHAR(30) NOT NULL,
PRIMARY KEY (`componentno`)
)
COLLATE='hp8_english_ci'
ENGINE=InnoDB
AUTO_INCREMENT=20
;
For the flatpackcomponents_apn table (the table in contention) I have tentatively put the following code:
CREATE TABLE `flatpackcomponents_apn` (
`flatpackid` INT(11) NOT NULL DEFAULT '12',
`componentno` INT(11) NOT NULL DEFAULT '23',
`quantity` INT(10) NOT NULL,
PRIMARY KEY (`componentno`, `flatpackid`),
INDEX `flatpackid` (`flatpackid`),
INDEX `componentno` (`componentno`),
CONSTRAINT `flatpackcomponents_apn_ibfk_1` FOREIGN KEY (`flatpackid`) REFERENCES `flatpack_apn` (`flatpackid`),
CONSTRAINT `flatpackcomponents_apn_ibfk_2` FOREIGN KEY (`componentno`) REFERENCES `component_apn` (`componentno`)
)
COLLATE='hp8_english_ci'
ENGINE=InnoDB
;

i have a challenge relating what should be primary key and foreign key in my database tables

i am designing database tables for a real estate company. my head is clogged up .i cant figure out how to decide which columns will become primary keys,foreign keys and/or composite keys.
i have four tables; location, floors , typeOfProperty and features.
location table is the most basic table that has columns; locationLong, locationLat,locationName and propertyName. locationlong is the primary key in this table.
i created the location table and used locationlong as primary key because i figured out that every point on earth has a unique location Longitude.this is if i consider that positive and negative values are always unique.(i stand to be collected).
i have noted however that there are situations where i would want to identify a property on a certain location that has a building that has more than one floor.therefore i would like to figure out how my floors table needs to be constructed. i am thinking of having a location long column and a second
column called floor number such that both these columns will make composite primary key of this table.
There is a third table called typeOfProperty. this is the table where i want to have different columns that select the type of property that can be on a particular floor. i.e a floor can have many houses to buy, many houses to let, a commercial property to sell, etc. so i have created the following columns;
hseBuyOrLetOrFurn ENUM('buy', 'let', 'furn') - SELECT IF HOUSE IS TO BUY, LET,
OR FULLY FURNISHED
comspaceBuyOrLease ENUM('buy', 'lease') - TO SELECT IF COMMERCIAL SPACE IS BUY
OR LEASE
cost INT -- TO CAPTURE COST OF PROPERTY ETC.
i would want to know what to use as primary key in this table.
there is a third table called general features . this table has columns that has columns that show the features of a particular type of property e.g it has a column for No of bedrooms, cctv,swimming pool, bathrooms,lifts, etc.
i have other similar tables to the general features as shown in the code below.
please assist me to know how i should figure out primary and foreign keys in this table.
CREATE TABLE `location` (
`locationLong` decimal(11,8) NOT NULL,
`locationLat` decimal(10,8) NOT NULL,
`locationName` varchar(35) NOT NULL,
`houseNumber` int(11) DEFAULT NULL,
PRIMARY KEY (`locationLong`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
CREATE TABLE `floors` (
`locationLong` decimal(11,8) NOT NULL,
`locationLat` decimal(10,8) NOT NULL,
`locationName` varchar(35) NOT NULL,
`id` int(11) DEFAULT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`ld`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
CREATE TABLE `propertytype` (
`locationLong` decimal(11,8) NOT NULL,
`locationLat` decimal(10,8) NOT NULL,
`hseBuyOrLetOrFurn` enum('buy','let','furn') DEFAULT NULL,
`bedrooms` int(11) DEFAULT NULL,
`gatedOrSloneOrApart` enum('gated','slone','apart') DEFAULT NULL,
`hotelOr` tinyint(4) DEFAULT NULL,
`gdwnBuyOrLease` enum('gdwn','lease') DEFAULT NULL,
`landBuyOrLease` enum('buy','lease') DEFAULT NULL,
`comspaceBuyOrLease` enum('buy','lease') DEFAULT NULL,
`twoDImage` blob,
`threeDImage` blob,
`vRVideo` blob,
`cost` int(10) unsigned NOT NULL,
`location_locationLong` decimal(11,8) NOT NULL,
PRIMARY KEY (`locationLong`),
KEY `fk_propertyType_location_idx` (`location_locationLong`),
CONSTRAINT `fk_propertyType_location` FOREIGN KEY (`location_locationLong`) REFERENCES `area` (`locationLong`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1
CREATE TABLE `generalfeatures` (
`locationLong` decimal(11,8) NOT NULL,
`locationLat` decimal(10,8) NOT NULL,
`livingAreaAndSize` int(11) NOT NULL,
`bedrooms` int(11) NOT NULL,
`bathrooms` int(11) NOT NULL,
`masterEnsuite` tinyint(1) NOT NULL,
`bedroomsWithBathrooms` tinyint(4) NOT NULL,
`kitchenAndSize` tinyint(4) NOT NULL,
`parkingAndSlots` tinyint(4) NOT NULL,
`swimmingPool` tinyint(1) NOT NULL,
`liftsAndNumber` tinyint(4) NOT NULL,
`CCTV` tinyint(1) NOT NULL,
`sizeOfLand` int(11) NOT NULL,
`borehole` tinyint(1) NOT NULL,
`propertyType_locationLong` decimal(11,8) NOT NULL,
PRIMARY KEY (`locationLong`),
KEY `fk_generalFeatures_propertyType1_idx` (`propertyType_locationLong`),
CONSTRAINT `fk_generalFeatures_propertyType1` FOREIGN KEY (`propertyType_locationLong`) REFERENCES `propertytype` (`locationLong`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1
CREATE TABLE `hotelfeatures` (
`locationLong` decimal(11,8) NOT NULL,
`locationLat` decimal(10,8) NOT NULL,
`conference` tinyint(1) NOT NULL,
`fibreCable` tinyint(1) NOT NULL,
`spa` tinyint(1) NOT NULL,
`freshOutdoor` tinyint(1) NOT NULL,
`laundryFacilities` tinyint(1) NOT NULL,
`entertainment` tinyint(1) NOT NULL,
`wifi` tinyint(1) NOT NULL,
`propertyType_locationLong` decimal(11,8) NOT NULL,
PRIMARY KEY (`locationLong`),
KEY `fk_hotelFeatures_propertyType1_idx` (`propertyType_locationLong`),
CONSTRAINT `fk_hotelFeatures_propertyType1` FOREIGN KEY (`propertyType_locationLong`) REFERENCES `propertytype` (`locationLong`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1
CREATE TABLE `outdoorfeatures` (
`locationLong` decimal(11,8) NOT NULL,
`locationLat` decimal(10,8) NOT NULL,
`gym` tinyint(1) NOT NULL,
`matureGardens` tinyint(1) NOT NULL,
`partyArea` tinyint(1) NOT NULL,
`gardenAndSize` tinyint(1) NOT NULL,
`waterFront` tinyint(1) NOT NULL,
`propertyType_locationLong` decimal(11,8) NOT NULL,
PRIMARY KEY (`locationLong`),
KEY `fk_outdoorFeatures_propertyType1_idx` (`propertyType_locationLong`),
CONSTRAINT `fk_outdoorFeatures_propertyType1` FOREIGN KEY (`propertyType_locationLong`) REFERENCES `propertytype` (`locationLong`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1
I want to have a general idea how the location table that have location details, links to floors table that has details of floor type links to the propertytype table that links to different property type and finally how this property type table links to the generalfeatures, hotel features and indoor features table.
You have a table to hold property main data (this table later you add to it more fields as required until I get the final design for table)
Ex: main_property_file( property_id PK , address, GPS_location )
Then you need to know is it for lease or sale ,
Build lookup table hold this , ex: property_for(typefor PK, name this)
And going to add a filed in previous main_property_file for typefor filed as foreign key
And so on until you put all business data structure , then going to review the tables and relation for consistency, you can put this in visual tool if you cannot imagine the relation and the data each table hold, and finally ask your model with query to find information or enter new data and so on to be sure your table design is complete and review the constraints too.

Create a datatype in a table that is a list of references to other table

I need to create a database with the following idea:
Preparing questions:
The teacher builds a pool of questions for use in the exams. The question includes a text and four answers. One of the answers is marked as the correct answer.
Each question in the database matches one subject, and one or more courses on the subject.
Each question has a number that identifies it uniquely, 5 digits.
For example: No. 02105: Subject: Mathematics (02), question number (105).
Preparation for exams:
The teacher builds exams that include questions from the database. Each exam has a number that identifies it in some way
Unique, 6 digits.
For example: 020301: Subject: Mathematics (02), Course: Algebra (03), Exam Number (01)
The duration of the assigned solution (in minutes) and the number of points per question is defined.
I created those tables:
CREATE TABLE `course` (
`idcourse` varchar(2) NOT NULL,
`courseName` varchar(45) DEFAULT NULL,
PRIMARY KEY (`idcourse`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
--
CREATE TABLE `subject` (
`idsubject` varchar(2) NOT NULL,
`subjectName` varchar(45) DEFAULT NULL,
PRIMARY KEY (`idsubject`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
--
CREATE TABLE `question` (
`questionText` varchar(100) DEFAULT NULL,
`answer1` varchar(100) DEFAULT NULL,
`answer2` varchar(100) DEFAULT NULL,
`answer3` varchar(100) DEFAULT NULL,
`answer4` varchar(100) DEFAULT NULL,
`subjetID` varchar(2) NOT NULL,
`questionNum.` varchar(3) NOT NULL,
PRIMARY KEY (`subjetID`,`questionNum.`),
CONSTRAINT `idsubject` FOREIGN KEY (`subjetID`) REFERENCES `subject` (`idsubject`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1
--
CREATE TABLE `exam` (
`subjectID` varchar(2) NOT NULL,
`courseID` varchar(2) NOT NULL,
`examNumber` varchar(2) NOT NULL,
`duration` int(11) DEFAULT NULL,
`pointsPerQuestionl` int(11) DEFAULT NULL,
PRIMARY KEY (`subjectID`,`courseID`,`examNumber`),
KEY `idCourse_idx` (`courseID`),
CONSTRAINT `idCo` FOREIGN KEY (`courseID`) REFERENCES `course` (`idcourse`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `idSu` FOREIGN KEY (`subjectID`) REFERENCES `subject` (`idsubject`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1
About the tables, I not sure if I had created them correctly
In exam I have number of questions.
For each question I need to define number of points.
How do I make this on my table relation?
Thanks.
Try this out:
select a.subjectname,b.questionText
from
subject a
left join
question b
on a.idsubject = b.subjectid;
You can proceed in the similar for the second problem.

Creating composite primarykey using a foreignkey and a non key attribute

This is my auto generated code after creating the batch table. while inserting data to this table
BatchID=1,Course_CourseID=1
BatchID=1,Course_CourseID=2
it is creating an error saying "Duplicate entry '1' for key 'BatchID_UNIQUE'".
I'm using C# 2010 express windows application as well as MySQl 5.1
My table schema is here
CREATE TABLE `batch` (
`BatchID` int(11) NOT NULL,
`Course_CourseID` int(11) NOT NULL,
`NoOfStudents` int(11) DEFAULT NULL,
`ClassRoom` varchar(45) DEFAULT NULL,
`StartDate` varchar(45) DEFAULT NULL,
`Day` varchar(45) DEFAULT NULL,
`Time` varchar(45) DEFAULT NULL,
PRIMARY KEY (`BatchID`,`Course_CourseID`),
UNIQUE KEY `BatchID_UNIQUE` (`BatchID`),
KEY `fk_Batch_Course1` (`Course_CourseID`),
CONSTRAINT `fk_Batch_Course1` FOREIGN KEY (`Course_CourseID`)
REFERENCES `course` (`CourseID`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Well, the error message quite clearly refers to this string:
UNIQUE KEY `BatchID_UNIQUE` (`BatchID`)
So what you have to do is either drop this index (with...
ALTER TABLE `batch` DROP INDEX `BatchID_UNIQUE`
... command, or just exclude this line from the table's definition (in CREATE TABLE).
All that said assuming that you really don't need your batch ids to be unique (in other words, there's no logical error in your INSERT statement. That seems to be the case, though: pair BatchID-Course_CourseID is already defined as unique (via PRIMARY KEY).
Try it this way. Drop your batch table and then run this sql. Rightly answered that you can not have two same vaues for a unique key. So I removed the unique key line as well.
CREATE TABLE IF NOT EXISTS `batch` (
`BatchID` int(11) NOT NULL,
`Course_CourseID` int(11) NOT NULL,
`NoOfStudents` int(11) DEFAULT NULL,
`ClassRoom` varchar(45) DEFAULT NULL,
`StartDate` varchar(45) DEFAULT NULL,
`Day` varchar(45) DEFAULT NULL,
`Time` varchar(45) DEFAULT NULL,
PRIMARY KEY (`BatchID`,`Course_CourseID`),
KEY `Course_CourseID` (`Course_CourseID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `batch` ADD CONSTRAINT `batch_ibfk_2` FOREIGN KEY (`Course_CourseID`)
REFERENCES `course` (`CourseId`) ON DELETE NO ACTION ON UPDATE NO ACTION;