Here is my sql script that I want to use to setup a database. Basically I've got people who are making choices, like a test/survey. I have some information about each person (person table) and their answers for each question (question table). Each person will answer multiple questions (so the primary key for the questions table is (id, qid).
Here's my problem. I want to store an array of integers associated with each question. So I've created a third table, array, whose primary key is (id, qid, idx), where idx is the index of the value in the array. Both the id and qid should be have a corresponding entry in the questions table, so I've made these foreign keys, but I get the common 150 errno when i do this. And I'm not sure why.
CREATE TABLE person (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
age INT,
income INT
);
CREATE TABLE questions (
id INT NOT NULL,
qid INT NOT NULL,
a INT,
b INT,
c INT,
PRIMARY KEY (id, qid),
FOREIGN KEY (id) REFERENCES person(id)
);
CREATE TABLE array (
id INT NOT NULL,
qid INT NOT NULL,
idx INT NOT NULL,
array_value INT NOT NULL,
PRIMARY KEY (id, qid, idx),
FOREIGN KEY (id) REFERENCES person(id),
FOREIGN KEY (qid) REFERENCES questions(qid)
);
This script does not work. If you remove the very last line which tried to set up a foreign key for qid, the script will run without error.
What is the error I'm making in trying to create this foreign key?
The quick fix is to change that foreign key constraint reference the PRIMARY KEY of the questions table. Since the PRIMARY KEY is defined as the combination of two columns, the foreign key will need to be the same:
FOREIGN KEY (id,qid) REFERENCES questions(id,qid)
With the syntax you have, the error is because the questions table does not have an index with qid as the leading index. If you added such an an index on questions, then you could create a foreign key that references the column qid. The InnoDB allows a non-unique key to be referenced by a foreign key, but... you don't want to do that. That's a non-standard extension. And the documentation warns against it.
The normal pattern is to have the PRIMARY KEY (or a UNIQUE KEY) as the target of a foreign key, which is what the foreign key definition (above) does.
FOLLOWUP
Your model looks fine.
But my personal preference would be to have a single column as the PRIMARY KEY of the question table. (I also name all tables in the singular, to match what the developers are going to name their Class.)
person
id (PK)
question
id (PK)
person_id (FK references person.id)
I wouldn't name that third table "array", I'd give it a different name. I'd name it as what "one" of those integer values represents, but it's not clear to me what those integer values really are.
score
id (PK)
question_id (FK references question.id)
idx
score_value
That model just suits my personal preferences. What you have is certainly workable.
Column qid in table questions has no guaranteed uniqueness. This is a requirement of the target key
of a foreign key. So, target is either a Primary key or has a Unique constraint.
Did you perhaps mean:
FOREIGN KEY (id, qid) REFERENCES person(id, qid)
Related
Which is better method among below:-
Using unique column name for each column, primary and foreign keys among all table.
Example 1:
CREATE TABLE projects (
project_id PRIMARY KEY,
project_name VARCHAR(30)
client_id INT,
fk_project_user_id INT, ( FOREIGN KEY )
projects_created_by INT, ( FOREIGN KEY )
);
CREATE TABLE clients (
client_id PRIMARY KEY,
client_name varchar(20),
fk_client_user_id INT,( FOREIGN KEY )
client_created_by INT, ( FOREIGN KEY )
)
Don't care about the uniqueness of each column name for each primary and foreign keys among all tables.
Example 2:
CREATE TABLE projects (
id PRIMARY KEY,
project_name VARCHAR(30)
client_id INT, ( FOREIGN KEY )
fk_user_id INT, ( FOREIGN KEY )
created_by INT ( FOREIGN KEY )
);
CREATE TABLE clients (
id PRIMARY KEY, (Same as above table)
client_id INT,
client_name varchar(20),
fk_user_id INT, ( FOREIGN KEY ) (Same as above table)
fk_client_id int, ( FOREIGN KEY )
created_by INT ( FOREIGN KEY ) (Same as above table)
);
When we plan database for big ERP having multiple tables and relationships among all? I have used a different name for each key to avoiding ambiguous error when we join two tables.
What is the best solution?
Naming conventions are up to you. Which naming convention you decide to use is not important. What's important is that you follow your own convention consistently, and document it so that other developers know how to understand your code and your schema.
Some people choose to give every table a primary key named id. If every one of their tables must have a column named id, then they can write reusable code for certain queries against any table.
However, this convention does not account for compound primary keys. Also if your query does a join, the query result set may have multiple columns named id unless you define column aliases.
When I design a database, I name my primary key in a descriptive way. projects.project_id for example. This avoids the problem of duplicate column names in a result set of a join. It also makes it more clear what the column means when you see it in a query or a result set.
I like to name the foreign key the same as the primary key column it references, when I can do it without resulting in a conflict.
But consider this example, where there are multiple foreign keys in the same table that reference Users.user_id.
CREATE TABLE Bugs (
bug_id INT PRIMARY KEY,
description TEXT NOT NULL,
reported_date DATETIME NOT NULL,
user_reported_by INT NOT NULL,
user_assigned_to INT,
user_verified_by INT,
FOREIGN KEY (user_reported_by) REFERENCES Users(user_id),
FOREIGN KEY (user_assigned_to) REFERENCES Users(user_id),
FOREIGN KEY (user_verified_by) REFERENCES Users(user_id)
);
You can't assume you can use a common column name, because it's normal to need multiple foreign keys referencing the same table, as in the example above. Therefore you must allow the FK column name to be different from the PK it references.
I want to know how to use a foreign key in a table,
I have a code here:
create table penerbit_buku(
id_buku char(8),
foreign key(id_buku) references buku(id_buku),
id_penerbit char(3),
foreign key(id_penerbit) references penerbit(id_penerbit)
)
Can I use this code instead:
create table penerbit_buku(
id_buku char(8) references buku(id_buku),
id_penerbit char(3) references penerbit(id_penerbit)
)
I have tried both and it succeed, is that correct?
No, MySQL parses but ignores the standard inline REFERENCES syntax.
When you declare a foreign key along with an individual column definition, it accepts the syntax as legitimate SQL, but then does not store the foreign key constraint. There's no error reported, but it's as if you didn't write the foreign key syntax at all.
You must declare foreign keys as table-level constraints (your first example above).
This is a case where MySQL is missing a feature of standard SQL. The issue was reported back in 2004, but never fixed! https://bugs.mysql.com/bug.php?id=4919
The reason for this issue is that historically, foreign key constraints were not supported by MySQL itself, but by the InnoDB storage engine, which was made by another company back then. They had to implement their own parser for CREATE TABLE and ALTER TABLE to support foreign keys, and they didn't feel like going the extra steps to support inline foreign key syntax, when table-level foreign key syntax would work.
The architect of InnoDB posted this response:
[6 Sep 2006 10:03] Heikki Tuuri
This will be fixed in MySQL foreign keys, when they are available for all table types.
The MySQL project is gradually working their way toward integrating foreign keys and similar features directly into the MySQL product. Perhaps in a few more years we'll see better support for standard FK syntax.
EXAMPLE:
CREATE TABLE Orders (
ID int NOT NULL,
Number int NOT NULL,
PersonID int,
PRIMARY KEY (ID),
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);
The foreign key must be referencing a primary key in another table
create table penerbit_buku
(id_buku char(8),
id_penerbit char(3),
foreign key(id_buku) references buku(id_buku),
foreign key(id_penerbit) references penerbit(id_penerbit)
);
I would need to see your other tables to give better help in the code
You can use this:
ALTER TABLE `table1`
ADD CONSTRAINT `FK_table1_table2` FOREIGN KEY (`fk_id`) REFERENCES `table2` (`id`);
first lets look at the description of FOREIGN KEY.
A FOREIGN KEY is a key used to link two tables together.
or
A FOREIGN KEY is a field (or collection of fields) in one table that refers to the PRIMARY KEY in another table.
Usually a table that has the foreign key is the child table. and the other table is the reference or parent table.
Since i Can not see your tables, ill give you different example.
Look at the following two tables:
Persons table:
Personal_id LastName FirstName age
1 pretty bob 20
2 angry jack 30
3 happy sue 28
Order Table:
OrderID OrderNumber Personal_id
1 77895 3
2 44678 3
3 22456 2
4 24562 1
Now look how Personal_id column in Orders table points to Personal_id in persons table.
The Personal_id in persons table is the primary key and the Personal_id in the orders table is the FOREIGN KEY.
now except linking how does foreign key help:
two general ways that i can think of:
1- foreign key is like a constrain that makes sure no action would destroy the links between tables
2- foreign key also acts as a constrain to stop invalid data from being inserted into the foreign key column, as it has to reference to the primary key column in the other table
code example in MySql:
CREATE TABLE Orders (
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (Personal_id) REFERENCES Persons(Personal_id)
);
code example is SQL-Server/MS Access/ Oracle:
CREATE TABLE Orders (
OrderID int NOT NULL PRIMARY KEY,
OrderNumber int NOT NULL,
PersonID int FOREIGN KEY REFERENCES Persons(Personal_id)
);
Primary key of Orders table is the orderID.
Foreign key of Orders table is what links it to persons table.
Personal_id columns are the columns that link both tables.
Both of the code chunks do the same depends what are you working with.
real world example:
assuming:
customer_Table column to be a primary key in restaurant table and foreign key in orders table.
if a waiter is putting customer_Table number 20 in the machine, and he puts customer_Table 200 by mistake such key does not exist as a primary key in restaurant table so he cant.
Extra:
what if you want to allow naming of the FOREIGN KEY constraint, and define a FOREIGN KEY constraint on many columns?
MySQL / SQL Server / Oracle / MS Access:
CREATE TABLE Orders (
OrderID int NOT NULL,
OrderNumber int NOT NULL,
Personal_id int,
PRIMARY KEY (OrderID),
CONSTRAINT FK_PersonOrder FOREIGN KEY (Personal_id)
REFERENCES Persons(Personal_id)
);
I have 3 tables:
class_a
CREATE TABLE class_a (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
std_id INT NOT NULL UNIQUE,
name varchar(225) NOT NULL)
class_b
CREATE TABLE class_b (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
std_id INT NOT NULL UNIQUE,
name varchar(225) NOT NULL)
sn_number
CREATE TABLE sn_number (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
pin INT NOT NULL UNIQUE,
serial VARCHAR(255) NOT NULL UNIQUE,
std_id INT NULL DEFAULT NULL,
FOREIGN KEY(std_id) REFERENCES class_a(std_id)
)
How can I reference unique std_id in class_a and class_b table as a foreign key in sn_number table.
I want to achieve something like ALTER TABLE sn_number ADD FOREIGN KEY(std_id) REFERENCES class_a(std_id), class_b(std_id)
I have tried doing this ALTER TABLE sn_number ADD FOREIGN KEY(std_id) REFERENCES class_a(std_id)
followed by
ALTER TABLE sn_number ADD FOREIGN KEY(std_id) REFERENCES class_b(std_id) on sn_number table but will keep overwriting each other.
I have read these:
Foreign Key Referencing Multiple Tables and
Composite key as foreign key (sql)
But I can't find the solution to the problem am having.
Foreign key must reference only one parent table. This is fundamental to both SQL syntax, and relational theory.
What you can do, is add another table classes or students that contain all std_id , then just reference the FK to it.
Since you haven't explicitly given a constraint name in your FOREIGN KEY declarations, the DBMS makes one up from the table name sn_number. Your problem is that you are thus implicitly declaring the same constraint name each time, so the old info for the name is lost. Just use different explicit constraint names for different cases of table & column list REFERENCES table & column list.
CONSTRAINT fk_sn_number_a FOREIGN KEY(std_id) REFERENCES class_a(std_id)
CONSTRAINT fk_sn_number_b FOREIGN KEY(std_id) REFERENCES class_b(std_id)
Just learn about the basics of Using FOREIGN KEY Constraints.
PS As remarked in a comment, this is a poor design. But contrary to the comment & another answer, your need for two foreign keys from the same table & column list is not a symptom of poor design. But notice that the problems that people usually have with "Foreign Key Referencing Multiple Tables" in questionable designs is that they think that their tables as designed need a foreign key from one place to two places when they don't. Such a design doesn't even involve a foreign key, it just involves something reminiscent of a foreign key.
I have been trying to create a foregin key with nbrseats but I i get the error 1005 all the time.
CAn someone help me!?
create table theater (
name varchar(30) primary key,
nbrseats int not null
) ENGINE=INNODB;
create table reservation (
nbr integer auto_increment,
users_username varchar(30),
cinemashow_showdate date,
movies varchar(30),
nbrseats int not null,
primary key (nbr),
foreign key (nbrseats) references theater(nbrseats),
foreign key (users_username) REFERENCES users(username)
on delete cascade,
foreign key (cinemashow_showdate, movies) references cinemashow(showdate, movie_title)
on delete cascade
) ENGINE=INNODB;
In order to be a FOREIGN KEY in another table, you must have an index created on theater.nbrseats. And in order to be able to reference a specific row reliably, it should therefore be a UNIQUE index. Otherwise, if you have duplicate values, the referencing table won't be able to discern which row it references. Even though InnoDB will allow you to create the relationship on a non-unique index, it is likely not the behavior you are looking for.
See this question for more info on that bit.
create table theater (
name varchar(30) primary key,
nbrseats int not null,
UNIQUE INDEX `idx_nbrseats` (nbrseats)
) ENGINE=INNODB;
The same will be true of the other FOREIGN KEY definitions in your table reservation, though we do not see their referenced tables posted here. The rules are:
The referenced column must be indexed (independently of any other compound indexes on it)
The referencing column must have exactly the same data type.
This kind of calls into question your design, however. If you are attaching a number of seats to a reservation, will the reservation number of seats exactly match the number available in the theater? Also this means that you could not have 2 theaters with the same number of seats.
You may need to reconsider your design here, and perhaps create a FOREIGN KEY that references theater.name instead of theater.nbrseats.
What would be the code for creating a table with two foreign keys?
I have a USER table and a PICTURE table. Since a USER can be in many PICTURE and many PICTURE can be from a USER, I need a third table with both primary keys.
Thank you SO, as usual you are invaluable for a learning novice. :)
I can't speak specifically for mySQL but in most databases I have worked with you can put as many foreign keys as you need on a table. But you can only have one primary key. A third table with both keys is the right choice. Make a foreign key to each of the other two tables and a primary key consisting of both ids in the table.
If I understood correctly, you may need to do something like the following:
CREATE TABLE users (
user_id INT NOT NULL PRIMARY KEY,
name VARCHAR(50) NOT NULL
) ENGINE=INNODB;
CREATE TABLE pictures (
picture_id INT NOT NULL PRIMARY KEY,
filename VARCHAR(255) NOT NULL,
posted_by INT NOT NULL,
FOREIGN KEY (posted_by) REFERENCES users(user_id)
) ENGINE=INNODB;
CREATE TABLE users_in_pictures (
user_id INT NOT NULL,
picture_id INT NOT NULL,
PRIMARY KEY (user_id, picture_id),
FOREIGN KEY (user_id) REFERENCES users(user_id),
FOREIGN KEY (picture_id) REFERENCES pictures(picture_id)
) ENGINE=INNODB;
Note that each picture can be posted by a user. In fact the posted_by field is constrained by a foreign key that references the users table.
In addition, I assume that you want to tag pictures ala-facebook. In this case, you can use the third table, which is using a composite primary key on (user_id, picture_id) and both fields are also constrained to the appropriate table.