How can I limit INT in MySQL? [duplicate] - mysql

This question already has an answer here:
SQL Integer Range When Creating Tables
(1 answer)
Closed 1 year ago.
I'm creating a college grading system with Java. I have a credit number column in courses table. I want this credit number to be limited between 1 to 8. I don't want any other number to be entered. I'm a beginner.
CREATE TABLE courses(
id INT PRIMARY KEY,
course_name VARCHAR(50) NOT NULL,
credit_number BETWEEN 1 AND 8 NOT NULL,
course_description VARCHAR(255));

Use a check constraint:
CREATE TABLE courses (
id INT PRIMARY KEY,
course_name VARCHAR(50) NOT NULL,
credit_number int NOT NULL,
course_description VARCHAR(255),
CONSTRAINT chk_courses_credit_number CHECK (credit_number BETWEEN 1 AND 8)
);

Slight variation on the accepted answer -
You could also use TINYINT instead of INT, which would restrict the possible range to -128 to 127 (one byte), which is okay since you only need 1-8:
https://dev.mysql.com/doc/refman/5.7/en/integer-types.html
CREATE TABLE courses (
id INT PRIMARY KEY,
course_name VARCHAR(50) NOT NULL,
credit_number TINYINT NOT NULL,
course_description VARCHAR(255),
CONSTRAINT chk_courses_credit_number CHECK (credit_number BETWEEN 1 AND 8)
);

Related

How to create tables with columns that have range in MySQL?

I want to create a table for the following:
One pokemon must have and can only have one trainer.
One pokemon may evolve into many other pokemons.
The pokemon name has a maximum of 50 characters and can not be
blank.
The dex number has 3-numeric-digit and can not be blank.
The pokemon height is a whole number and ranges [0, 1,000] cm
inclusive.
The pokemon weight ranges [0.00, 1,000.00] kg inclusive.
The pokemon color has a maximum of 20 characters.
The pokemon type has a maximum of 15 characters. If an INSERT
doesn't list the pokemon type value, it should default to Grass
I am stuck specifically on number 5. How do I apply that to my table? Also, another question is how do I apply numbers 5-6 and 8 also? How can I also assign the EvolvedFrom as one of the Foreign Keys? I don't know where to refrence it. I am a little bit confused, so please help. Thank you so much.
Table Reference
ERD of the table to be created
This is my sample code that I have created:
CREATE TABLE pokemon(
pokemonId int,
pokemonDexNum int(3) NOT NULL,
pokemonName varchar(50) NOT NULL,
pokemonHeightCm int unsigned,
CONSTRAINT CHK_pokemonHeightCm CHECK (pokemonHeightCm <= 1000)
pokemonWeightKg int NOT NULL,
pokemonColor varchar(50),
pokemonType varchar(50),
trainerId int NOT NULL,
evolvedFrom varchar(50),
PRIMARY KEY (pokemonId),
FOREIGN KEY (trainerId) REFERENCES trainer(trainerId),
FOREIGN KEY (evolvedFrom) REFERENCES pokemon(evolvedInto) --THIS LINE IS INCORRECT. HELP--
);
Try to include a constrain as below.
CREATE TABLE pokemon(
pokemonHeightCm int() NOT NULL,
CONSTRAINT pokemonHeightCm_Ck CHECK (pokemonHeightCm BETWEEN 0 AND 1000),
... and the rest
Try the below, I haven't tested the syntaxes:
CREATE TABLE pokemon(
pokemonId int ,
pokemonDexNum int(3) NOT NULL, #rule 4
pokemonName varchar(50) NOT NULL, #rule 3
pokemonHeightCm int NOT NULL, CONSTRAINT CHK_pokemonHeightCm CHECK (pokemonHeightCm <= 1000), #rule 5
pokemonWeightKg decimal NOT NULL, CONSTRAINT CHK_pokemonWeightKg CHECK (pokemonWeightKg <= 1000.00), #rule 6
pokemonColor varchar(20), #rule 7
pokemonType varchar(15) NOT NULL DEFAULT 'Grass', #rule 8
trainerId int NOT NULL,
evolvedFrom int,
PRIMARY KEY (pokemonId), #rule 1
FOREIGN KEY (trainerId) REFERENCES trainer(trainerId), #rule 1
FOREIGN KEY (evolvedFrom) REFERENCES pokemon(pokemonId) #rule 2
);

modeling issue with field with 4 values (1 or more)

lets say I have an account object in my application, which currently represented as:
CREATE TABLE Account (
accountId int NOT NULL AUTO_INCREMENT,
name varchar(255) NOT NULL,
PRIMARY KEY (accountId)
);
Now, Account object need to also have Solution field...and Status have 4 different possible values:
Solution1, Solution2, Solution3, Solution4
What would be the right way to represent it in the database?
Account can have few statuses, and status can have few accounts...
So at first I thought create in the db table of Solutions and than have another table to hold the relationship, but its seems too complicated for a field that have only 4 possible values...
Create a junction table to represent the relationships between accounts and solutions:
CREATE TABLE account_solution (
accountId int NOT NULL,
solutionId int NOT NULL
PRIMARY KEY (accountId, solutionId)
)
For your solution table, since there are only 4 values, you might be able to take advantage of MySQL's enum type, e.g.
CREATE TABLE solution
solutionId int NOT NULL PRIMARY KEY,
status ENUM('Solution1', 'Solution2', 'Solution3', 'Solution4')
);
You can use set Mysql SET type
CREATE TABLE Account (
accountId int NOT NULL AUTO_INCREMENT,
name varchar(255) NOT NULL,
status set('Solution1','Solution2','Solution3','Solution4') NOT NULL,
PRIMARY KEY (accountId)
);
And if you want to select a specific status
SELECT *
FROM `Account`
WHERE FIND_IN_SET( 'Solution2', `status` ) >0

MySQL - add data into 2 tables and 1 has foreign key

I'm a totally MySQL newcomer. Sr if my question is quite obvious. I got 2 tables
CREATE TABLE tbl_addresses(
PK_ADDRESS_ID int NOT NULL AUTO_INCREMENT,
house_number int NOT NULL,
street varchar(35),
district varchar(35),
city varchar(35),
postcode varchar(8),
PRIMARY KEY (PK_ADDRESS_ID)
);
CREATE TABLE tbl_people(
PK_PERSON_ID int NOT NULL AUTO_INCREMENT,
title varchar(6) NOT NULL, # Master / Mister therefor 6 is max
forename varchar(35) NOT NULL,
surname varchar(35) NOT NULL,
date_of_birth DATE NOT NULL,
contact_number varchar(12) NOT NULL,
FK_ADDRESS_ID int NOT NULL,
PRIMARY KEY (PK_PERSON_ID),
FOREIGN KEY (FK_ADDRESS_ID) REFERENCES tbl_addresses (PK_ADDRESS_ID)
);
and I'm trying to import data into these tables from Java using below syntaxes
INSERT INTO tbl_addresses (house_number,street,district,city,postcode) VALUES ('1','abc','','abc','abc');
INSERT INTO tbl_people (title,forename,surname,date_of_birth,contact_number) VALUES ('Mr','Tri ','Nguyen','1991-1-1','0123456789');
I got an error Field 'FK_ADDRESS_ID'doesn't have a default value and data actually goes into tbl_addresses but not tbl_people. Am I missing anything? Thanks in advance!
This error is being caused by that you labelled the FK_ADDRESS_ID field in the tbl_people table as NOT NULL, yet you are trying to do an INSERT without specifying a value for this column.
So something like this would work without error:
INSERT INTO tbl_people (title, forename, surname, date_of_birth,
contact_number, FK_ADDRESS_ID)
VALUES ('Mr', 'Tri', 'Nguyen', '1991-1-1', '0123456789', 1);
You could also specify a default value for FK_ADDRESS_ID (the error message you got alluded to this). Here is how you could adda default value:
ALTER TABLE tbl_people MODIFY COLUMN FK_ADDRESS_ID int NOT NULL DEFAULT 1
But because FK_ADDRESS_ID is a key into another table, the value should really be based on the primary key in tbl_addresses.
The fact that you are using a foreign key isn't the reason that you are getting this error. Let's take a look at your column definition.
FK_ADDRESS_ID int NOT NULL,
This is not null but does not a default. Now a look at your insert statement
INSERT INTO tbl_people (title,forename,surname,date_of_birth,contact_number)
FK_ADDRESS_ID isn't in your column list but it cannot be null and doesn't have a default so what can mysql do? Produce an error of course.
The best bet is to define that column as nullable.
Let's revisit the foreign key constraint.
FOREIGN KEY (FK_ADDRESS_ID) REFERENCES tbl_addresses (PK_ADDRESS_ID)
What this really says is that if you asign a value to FK_ADDRESS_ID that value should be present in PK_ADDRESS_ID column in tbl_address
as a side note, it's customary to use lower case for table/column names.

Table localization - One column for a table

I have got only one column for a table when i create two localized tables. Code as bellow.
-- Month
CREATE TABLE `month` (
`id` INT PRIMARY KEY NOT NULL AUTO_INCREMENT,
);
-- Month Localized
CREATE TABLE `month_loc` (
`month_id' INT NOT NULL,
`name` VARCHAR(200) NOT NULL,
`description` VARCHAR(500) NOT NULL,
`lang_id` INT NOT NULL
);
month_loc.month_id is the foreign key.
month table holds only the primary key. Other all fields should be localized. Is this table structure correct ?
Thanks.
If correct implies a certain degree of normalization, and the content of your columns name and description vary per month_id, lang_id (which would be the combined primary key of month_loc), then yes, your design has reached the 3rd grade of normlization.

CakePHP model question, How can i make table relationship for polls and quiz?

Suppose i want to create polls and quiz with a question and with several options as answers.
Do i have to create Poll model for this ?
How can i track the percentage result for every option in polls table ?
Should i make another table with polls answer options ?
What would be the table relationship for polls question and polls answer ?
Is this correct way?
create table polls (id integer not null auto_increment primary key, question varchar(300) not null, mark tinyint not null, created datetime, modified datetime);
create table pollsanswers (id integer not null integer auto_increment primary key, poll_id integer not null, answer varchar(500) not null, mark tityint not null, created datetime, modified datetime);
create table quizes (id integer not null auto_increment primary key, question varchar(300) not null, mark tinyint not null, created datetime, modified datetime);
create table quizesanswers (id integer not null integer auto_increment primary key, quiz_id integer not null, answer varchar(500) not null, mark tityint not null, created datetime, modified datetime);
If i make a mysql table polls , then can i access and use that table with posts or other controller or must i create polls_controller.php and poll.php model ?
Can i do this without making new model and controller ?
If it's me, I'd probably have the following tables:
create table polls (
id integer not null auto_increment primary key,
created datetime,
modified datetime
);
create table quizzes (
id integer not null auto_increment primary key,
created datetime,
modified datetime
);
create table questions (
id integer not null auto_increment primary key,
model varchar(255) not null, -- Poll or Quiz, in this scenario
foreign_key integer not null,
question varchar(255) not null,
created datetime,
modified datetime
);
create table answers (
id integer not null auto_increment primary key,
question_id integer not null,
answer varchar(255) not null,
created datetime,
modified datetime
);
My associations would probably be this:
Poll hasMany Question
Quiz hasMany Question
Question belongsTo Poll, Quiz
Question hasOne Answer
Answer belongsTo Question
Since both polls and quizzes have component questions, I'd try to consolidate that aspect. In order to account for both relationships, I'd make Question polymorphic.