CREATE TABLE Game
(
GameID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
DatePlayed DATE NOT NULL,
BoardNum TINYINT NOT NULL,
Score ENUM('1-0', '0-1', '2-2') NOT NULL,
MatchID INT NOT NULL,
WhitePlayer CHAR(20) NOT NULL,
BlackPlayer CHAR(20) NOT NULL,
CONSTRAINT fk_MatchID FOREIGN KEY (MatchID) REFERENCES MatchPlay (MatchID),
CONSTRAINT fk_WhitePlayer FOREIGN KEY (WhitePlayer) REFERENCES Player (PlayerName),
CONSTRAINT fk_BlackPlayer FOREIGN KEY (BlackPlayer) REFERENCES Player (PlayerName)
);
I'm unable to find a solution online, maybe someone can help. The Score entity above I am looking a data type that would save the data input say 4-2, 2-1, 1-0 example. Something like this format [0-9]-[0-9] . So basically, it wont allow the user to enter 10-0 only between [0-9]-[0-9] . Also would it be ENUM or different data type.
I think it's not possible to use SQL that way.
Data manipulation should not occur in the sql, it's better in the controller if you use MVC concept.
It's much safer.
in your case, you can use varchar or integer datatype as alternative.
Related
I am unable to create these tables in MySQL. Everything looks complete to me but I keep getting errors.
Here is my SQL:
CREATE TABLE Movies(
title char PRIMARY KEY NOT NULL,
Years date NOT NULL,
length decimal not null,
genre char NOT NULL,
academy_award char not null,
FOREIGN KEY(the_name) REFERENCES Studio,
FOREIGN KEY(directorName) REFERENCES Director);
CREATE TABLE StarsIn(
FOREIGN KEY(title) REFERENCES Movies,
FOREIGN KEY(Years) REFERENCES Movies,
FOREIGN KEY(the_name) REFERENCES MovieStar);
CREATE TABLE Director(
the_name char PRIMARY KEY NOT NULL,
birthdate date NOT NULL,
nationality char NOT NULL);
CREATE TABLE MovieStar(
the_name char PRIMARY KEY NOT NULL,
birthdate date NOT NULL,
address char NOT NULL,
gender char NOT NULL);
CREATE TABLE Studio(
the_name char PRIMARY KEY NOT NULL,
address char NOT NULL);
This isn't working because your tables are not being created in the proper order.
The parent table must always be created first, because otherwise you will be trying to reference a column that does not exist.
For example, look at this part here:
CREATE TABLE Movies(title char PRIMARY KEY NOT NULL, Years date NOT NULL,
length decimal not null, genre char NOT NULL, academy_award char not null,
FOREIGN KEY(the_name) REFERENCES Studio, FOREIGN KEY(directorName) REFERENCES Director);
You can't reference tables studio or director because they don't even exist.
The proper order could be:
Studio
Movie Star
Director
Movies
StarsIn
In addition, you have a lot of other problems going on here.
You do not define any columns in the Stars IN table, you only declare foreign keys:
CREATE TABLE StarsIn(
FOREIGN KEY(title) REFERENCES Movies,
FOREIGN KEY(Years) REFERENCES Movies,
FOREIGN KEY(the_name) REFERENCES MovieStar);
Not only are you not defining any columns, you aren't referencing anything. This will also throw an error. Your foreign key title must reference some column in the movies table. And in addition to that, you can't create a foreign key reference for Years. Mostly because you cannot create a foreign key to a column that is not primary key in another table, and also why should you need two foreign keys to the same table?
Those problems exist in other create table statements as well, so given everything I've said please go back and look at each of your create table statements.
Here is a working SQL Fiddle you can use for reference though.
EDIT
I would like to also add that I do not recommend using the char datatype. Please look into using VARCHAR().
The problem you are having is that you are referencing columns in tables that do not exist.
Although you create these tables later, the DBMS engine does not know they will exist.
The solution - create the tables without the FK's that do not exist, and add these later using the "ALTER TABLE" command.
It seems like you know the syntax, so I'll let you inform me if you cannot find it.
your syntax should look like (All I did is re-order, and change char to be archer...):
CREATE TABLE Studio(the_name varchar(50) PRIMARY KEY NOT NULL, address varchar(50) NOT NULL);
CREATE TABLE Director(the_name varchar(50) PRIMARY KEY NOT NULL, birthdate date NOT NULL, nationality varchar(50) NOT NULL);
CREATE TABLE Movies(title varchar(50) PRIMARY KEY NOT NULL, Years date NOT NULL,
length decimal not null, genre varchar(50) NOT NULL, academy_award varchar(50) not null,
the_name REFERENCES Studio(the_name), directorname REFERENCES Director(the_name));
CREATE TABLE MovieStar(the_name char PRIMARY KEY NOT NULL, birthdate date NOT NULL, address char NOT NULL, gender char NOT NULL);
CREATE TABLE StarsIn(title REFERENCES Movies(title),movie REFERENCES Movies(title), moviestar REFERENCES MovieStar(the_name));
A little note, depends on the version - you'd might have to use the FOREIGN KEY(col_name) instead of col_name. I like more the syntax without it, but some versions force you to use FOREIGN KEY(title) instead of title in the last SQL for example.
The syntax you used - Foreign key NAME References TABLE (Column) -- you forgot the column-- Allows you to name the FK. If you don't use the "Foreign Key" the system will randomly assign a name. This is usually not important, unless you want the DB design to be "clean" and to be able to reference it by name.
P.S. - I did not run it, I trust you to inform if there's any other issue - I did not check the syntax, just fixed the error you reported- references that do not exist...
P.S. P.S. Always check syntax... http://dev.mysql.com/doc/refman/5.1/en/create-table.html
I want to represent a device who posses a led screen, a bunch of sensors, and some other properties. The thing is I know, in the future, we might need to store different kind of devices so I'm hesitating about how to represent in the database.
My first approach was a table like this:
CREATE TABLE device_name (
id STRING(32) NOT NULL UNIQUE,
led00 STRING(6) DEFAUTL "000000",...,
sensor_name_status BOOL,
sensor_name_data REAL,
....
owner STRING(32) NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (owner) REFERENCES users(id));
This way I represent the owner and device id with a md5 token as identifier and I have one field for each led and sensor.
Other approach was:
CREATE TABLE devices (
id STRING(32) NOT NULL UNIQUE,
owner STRING(32) NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (owner) REFERENCES users(id));
CREATE TABLE sensors (
device_id STRING(32) NOT NULL,
status BOOL,
data REAL,
type INT(3) NOT NULL,
PRIMARY KEY (device_id,type)
FOREIGN KEY (device_id) REFERENCES devices(id));
CREATE TABLE leds (
device_id STRING(32) NOT NULL,
value STRING(6) NOT NULL,
x INT(3) NOT NULL,
y INT(3) NOT NULL,
PRIMARY KEY (device_id,x,y),
FOREIGN KEY (device_id) REFERENCES (devices));
The second alternative seems conceptually better deal for me, cause it allows me to insert new devices with a consistent access interface but I'm worried about performance if I have just like 1-3 device models maybe will be better to have one device table for each one.
What are your thoughts? Any criticism is welcome :)
Your second approach is the right direction. This is clear from the first line of your question: "I want to represent a device who posses a led screen, a bunch of sensors, and some other properties." You have three different entities in the real world. Model them as three different entities.
Room for improvement. Use auto-incremented integer primary keys for the ids. I also prefer calling the id after the name of the table, so DeviceId is the primary key for that. That means that any join is "obvious" because the join fields are named the same or very similarly.
In addition, I think you need additional tables for Sensors and possibly LEDs. That is, the type information should be stored in a different table.
Here is my suggestion:
CREATE TABLE Devices (
DeviceID int not nullauto_increment primary key
Name varchar(32) NOT NULL UNIQUE,
Owner_UserId int NOT NULL,
FOREIGN KEY (Owner_UserId) REFERENCES users(Userid)
);
create table Sensors (
SensorId int not null auto_increment primary key,
Type int,
Name varchar(255)
);
CREATE TABLE sensors (
DeviceID int NOT NULL,
SensorID int not null,
status BOOL,
data REAL,
primary key (DeviceID, SensorId)
foreign key (DeviceID) REFERENCES devices(DeviceID),
foreign key (SensorId) REFERENCES sensors(SensorID),
);
CREATE TABLE leds (
DeviceID int not null,
value varchar(6) NOT NULL,
x INT(3) NOT NULL,
y INT(3) NOT NULL,
PRIMARY KEY (DeviceID, x, y),
FOREIGN KEY (DeviceID) REFERENCES devices(DeviceID)
);
In general, when creating tables, I also add two or three default columns at the end:
CreatedAt . . . the date/time when created (a timestamp column in MySQL)
CreatedBy . . . who created the column
CreatedOn . . . The server where the machine was created (if the system is going to span servers)
I have a set of users of different types, each type has individual set of fields storing user settings. My thought was to store user_id and user_type in one table with common set of fields and to move other settings to a separate tables. But the problem is how to link user from common table with his details in separate table. I see one solution is to store table name associated with certain user type in another table. But is it the best solution?
CREATE TABLE IF NOT EXISTS `mydb`.`user` (
`user_id` INT NOT NULL,
`user_name` INT NOT NULL,
`user_type` INT NULL,
PRIMARY KEY (`user_id`, `user_name`),
UNIQUE INDEX `adv_id_UNIQUE` (`user_id` ASC),
INDEX `adv_type_idx` (`user_type` ASC),
CONSTRAINT `adv_type`
FOREIGN KEY (`user_type`)
REFERENCES `mydb`.`user_type` (`type_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
CREATE TABLE IF NOT EXISTS `mydb`.`user_type` (
`type_id` INT NOT NULL,
`type_table` VARCHAR(45) NULL,
UNIQUE INDEX `type_id_UNIQUE` (`type_id` ASC),
PRIMARY KEY (`type_id`))
//TABLES WITH SEPARATE SET OF FIELDS
CREATE TABLE IF NOT EXISTS `mydb`.`user_details_admin` (
`user_id` INT NOT NULL,
`user_admin` VARCHAR(45) NULL,
PRIMARY KEY (`user_id`))
CREATE TABLE IF NOT EXISTS `mydb`.`user_details_moderator` (
`user_id` INT NOT NULL,
`user_moderator` VARCHAR(45) NULL,
PRIMARY KEY (`user_id`))
This appears to be a situation where you want to model inheritance in your database.
Rather than storing the user_details_ table names in the user_types table, something akin to the following may serve you better:
CREATE TABLE IF NOT EXISTS 'mydb'.'user' (
'user_id' INT NOT NULL,
'type_id' INT NOT NULL,
'commonfield1' datatype (NOT) NULL,
'commonfield2' datatype (NOT) NULL,
'commonfield...' datatype (NOT) NULL,
PRIMARY KEY ('user_id', (other field as needed)),
UNIQUE INDEX 'adv_id_UNIQUE' ('user_id' ASC),
INDEX 'adv_type_idx' ('type_id' ASC),
CONSTRAINT 'adv_type'
FOREIGN KEY ('type_id')
REFERENCES 'mydb'.'user_type' ('type_id')
ON DELETE NO ACTION
ON UPDATE NO ACTION)
CREATE TABLE IF NOT EXISTS 'mydb'.'user_type' (
'type_id' INT NOT NULL,
'type_name' VARCHAR(45) NOT NULL,
UNIQUE INDEX 'type_id_UNIQUE' ('type_id' ASC),
UNIQUE INDEX 'type_name_UNIQUE' ('type_name' ASC),
PRIMARY KEY ('type_id'))
//TABLES WITH SEPARATE SET OF FIELDS
CREATE TABLE IF NOT EXISTS 'mydb'.'user_details_admin' (
'user_id' INT NOT NULL,
'type_id' INT NOT NULL,
'adminfield1' datatype (NOT) NULL,
'adminfield...' datatype (NOT) NULL,
PRIMARY KEY ('user_id'))
CONSTRAINT user_type_FK
FOREIGN KEY ('user_id', 'type_id')
REFERENCES 'mydb'.'user' ('user_id', 'type_id')
ON DELETE NO ACTION
ON UPDATE NO ACTION)
CREATE TABLE IF NOT EXISTS 'mydb'.'user_details_moderator' (
'user_id' INT NOT NULL,
'type_id' INT NOT NULL,
'moderatorfield1' datatype (NOT) NULL,
'moderatorfield...' datatype (NOT) NULL,
PRIMARY KEY ('user_id'))
CONSTRAINT user_type_FK
FOREIGN KEY ('user_id', 'type_id')
REFERENCES 'mydb'.'user' ('user_id', 'type_id')
ON DELETE NO ACTION
ON UPDATE NO ACTION)
This design assumes that a user may be of one and only one type. You'll need to insure that, for example, a moderator is only added to the user_details_moderator table using triggers or views, and/or by handling it in your application code. MySQL doesn't implement check constraints on tables. You'll likely want to create views, anyway, in order to avoid having to write the JOIN between the user table and the sub-type tables every time you want to query a specific sub-type.
Note: The INDEX on type_id in the user table may not be useful or necessary.
This is not the only way to model your data. If you have few fields that are distinct between types and/or are willing to have fields you know will be NULL in your table, you can just add all the fields to the user table. Other than the a priori NULL fields issue, a major difference between these approaches comes with the addition of a new user_type with new distinct fields. In the example I provided, you would need to add a new table. In the single-table design, you would need to add new nullable fields to the user table. Which is easier to maintain is really up to you, but I personally prefer the table-per-type design because in my uses adding a table is relatively trivial and I dislike intentionally adding fields that I know will contain NULL 'values' without serious optimization advantages (that don't exist in my case, but might in yours).
See also How do you effectively model inheritance in a database?, and/or search for "inheritance" under the database tag for further information.
I think creating a user_type_parameters with columns user_id, parameter_key, parameter_value could be an interesting solution as it would give you more flexibility.
the parameter_key column would be the name of some parameter like one of the columns on the user_details_admin table, and on the parameter_value column you would inster its correspondent value.
Of course on the application side you would have to know what keys to expect for each user type.
please fell free to ask if you have any doubts about my explanation.
I have bulid a new table in my SQL database with the following command :
Create Table if not exists Images (ImageID int (10) primary key NOT NULL AUTO_INCREMENT ,
UserID int (10) NOT NULL,
Translated tinyint Default 0,
DeleteImage tinyint Default 0,
DataPosted date,
TheImage blob,
Translation text,
FOREIGN KEY (UserID) REFERENCES Users(UserID) ON DELETE CASCADE)
the table is been created just fine, but what i'm checking what was build i've found out that in the table the columns ImageID, TheImage, and Translation are defined as primary keys.
as the query is showing I want only the ImageId to be the primary key.
what's happening here?
tnx
Seems quite unlikely. It seems far more likely that something is wrong with whatever tool you're using to find out which columns are primary keys.
Actually, from the documentation - here: http://dev.mysql.com/doc/refman/5.1/en/create-table.html - it would follow that a MySQL table can only have one primary key. But even if not, why would you worry about it?
Hey guys i'm kind of new to the whole world of mysql, the current problem i have is that i can't quite work out why this is not working is it possibly to do with the 2 primary keys? Or is it the references? Thanks in advance
CREATE TABLE IsSeenBy
( PatientCode int (11) NOT NULL,
DoctorCode int (11) NOT NULL,
Date VARCHAR (10) NOT NULL,
Time VARCHAR (5) NOT NULL,
PRIMARY KEY (PatientCode),
PRIMARY KEY (DoctorCode),
PatientCode REFERENCES (Patient),
DoctorCode REFERENCES (Doctor)
;
Date is a reserved word so if you want to name a column that you will need to quote it. Also I'd highly recommend using an actual Date type for that column, not VARCHAR. (unless it needs to be something like a star date.) And yes, you cannot have two primary keys. You need either one or a compound one. Your foreign key definitions do not look correct either
CREATE TABLE IsSeenBy
(PatientCode int (11) NOT NULL,
DoctorCode int (11) NOT NULL,
`Date` DATETIME NOT NULL,
PRIMARY KEY (PatientCode, DoctorCode),
FOREIGN KEY (PatientCode)
REFERENCES Patient(PatientCode)
ON UPDATE CASCADE ON DELETE RESTRICT,
FOREIGN KEY (DoctorCode)
REFERENCES Doctor(`DoctorCode`)
ON UPDATE CASCADE ON DELETE RESTRICT
);
You can't have 2 PK in the table. If you want composite PK use
PRIMARY KEY (PatientCode, DoctorCode),
instead.
You must explore Foreign key reference documentation too.