Having trouble referencing foreign keys in sqlfiddle - sqlfiddle

I'm very new to coding and am having loads of trouble figuring out my 2 current problems. For the first one, I have created a table called "sales" that has a primary key, donutorder, but the table also has a foreign key customerid. I have tried writing the code but I keep getting errors in SQLFIDDLE. The second one is similar but donutorder and donutid are both primary and foreign keys in the "orderline" table. I don't know how to write the code because of the 2 foreign keys. Can any one help? Thank you very much for your help.

Glad to hear you're having the same problem. I'm working on the same project.
After problems with the first table and the CustomerID foreign key, I omitted the foreign key and continued creating the other tables. It's interesting that I successfully completed another table with 2 foreign keys and it was fine. I have Googled everything related, including indexes (which I think may be part of the problem).
If you create all of your tables without the CustomerID foreign key reference, they will be successful. The problem shows up after the inserts and when retrieving table results. The Customer ID comes up "NULL". (At least it did on mine.)
I'm tempted to try one more time omitting the CustomerID foreign key and try to recoup with a JOIN query.
If you have any brilliant ideas, I hope you will reply.
PS About your second question--You have to put the (DonutOrderID,DonutID) as PRIMARY KEY; then 2 "Foriegn Key" lines-- one for DonutOrderID and another for DonutID with 'REFERENCES' to the associated table and field.
TH

Related

How do I make a field reference another field which is not a primary key in MySQL?

I know that foreign keys need not reference only primary keys but they can also reference a field that has a unique constraint on it. For my scenario, I am setting up a quiz where for each test, I have a set of questions. My table design is like this
The point is, in my 2nd table where I will put all the answer options, I want the question number field to link to the first table question number. How do I do this? Or is there an alternative to this design?
Thank you
Ideally there should be a question_id primary key column in the test_question table, and you would use this as the foreign key in the test_answer table.
With your composite primary key in the test_question table, you should make a corresponding composite foreign key:
CONSTRAINT FOREIGN KEY (test_id, question_no) REFERENCES test_question (test_id, question_no)
This is in addition to the foreign key just for the test_id column.
Add another table purely for answers, and link them via the question_no field.
A DB table should hold information on one sort of item. Questions and answers are separate sorts of information so should be in separate tables. Adding a separate table also allows changes to questions and answers independently. Additionally, if they are separate, you could add a language field to each table and have a multi-lingual quiz
Short answer:
You can JOIN on any columns or expressions. There is no "requirement" for a FOREIGN KEY, PRIMARY KEY, UNIQUE, or anything else.
Long answer:
However,... For performance (in large tables), some things make a difference.
If you are JOINing to a PK, Unique key, or even an indexed column, the query cold run faster.
Why have a FOREIGN KEY? An FK is two things:
A "constraint" that says that the value must exist in the other table. Also, with things like ON DELETE CASCADE, it can provide actions to take if the indicated row is removed. The constraint requires looking in the other table each time a write occurs (eg INSERT).
An Index. That is, specifying a FK automatically adds an INDEX (if not already present) to make the constraint faster.
Getting the id
Here is the "usual" way to do a pair of inserts, where you need the second to 'point' to the first:
INSERT INTO t1 ... -- with an AUTO_INCREMENT id
grab LAST_INSERT_ID() -- that id
INSERT INTO t2 ... -- and include the id from above
For AUTO_INCREMENT to work it must be the first column of some key. (Note: a PRIMARY KEY is a UNIQUE is a key (aka INDEX).)
Optionally you can specify a FK on the second table to point out the connection between the tables.
And, as spelled out in other answers, a FK could involve more than one column.
Entities and Relations
Sometimes, a set of tables like yours is best 'designed' this way:
Determine the "entities": users, tests, questions, answers
Relations and whether they are 1:1, 1:many, or many:many... Users:test is many-to-many; tests:questions is 1:many (unless you want questions to be shared between tests).
Answers is more complex since each 1 answer depends on the user and question.
1:1 -- rarely practical; may as well merge the tables together.
1:many -- a link (FK?) in one table to the other.
many:many -- need a bridge table with (usually) 2 columns, namely ids linking to the two tables.

When writing mySQL code, what's a better practice?

I'm learning mySQL, still on basic stuff.
My teacher has said that when writing, the best codes have first, all the tables; then, ALTER TABLE queries inserting keys to the tables. That way, we can properly name the keys. I know for sure he does that to foreign keys. He has taught this with primary keys examples as well; however, when providing files with answers for exercises he proposed, he typed the primary keys inside the tables, and later only altered the foreign keys.
How should I do it then? Always insert primary keys inside the tables, alter the foreign keys later? Or should I alter both primary and foreign keys? I'm currently trying to do he latter, and bumping into auto_increment issues for the primary keys.
Thank you for your insight!
You can't rename a primary key, so it makes no sense to do it later in an ALTER statement.
You're running into issues with auto_increment, because an auto_increment column also has to be (part of) the primary key. So you can not specify an auto_increment column but not make it primary key at the same time.
The thing is, this question is actually obsolete, as you can name your foreign keys also when creating the table. Which is for me the way that is prefered. Everything done in one statement. It would look like this:
CREATE TABLE foo (
id int auto_increment primary key,
bar int,
constraint my_fancy_fk_name foreign key (bar) references other_table(whatever_column)
);

Creating a table but with other entities in a compound key?

I have 2 Primary key tables and 1 Compound table.
I want to have some other information apart from the 2 primary keys from the primary key table in the compound table.
Would I just repeat this data or is their a way to add other fields into a the compound field without repeating it?
Thanks.
Your current design looks close to right. But I think your EventVolunteer table should look like this:
CREATE TABLE EventVolunteer (
eventID INTEGER,
volunteerID INTEGER,
FOREIGN KEY eventID REFERENCES Event(eventID),
FOREIGN KEY volunteerID REFERENCES Volunteer(volunteerID),
PRIMARY_KEY(eventID, volunteerID)
)
This bridge table should exist to store relationships between events and their volunteers, and nothing else. All metadata for events and volunteers should be in the Event and Volunteer tables, respectively.
If you need to bring in some information, then you can do so via joining the Event and Volunteer tables with this bridge table. This join is much less of a penalty than you might think, if you have indices setup in the right places.

How to refer to different tables from one column?

i have following db design(kept just essential informations):
TABLE monument
PRIMARY KEY id
name
TABLE restorer
PRIMARY KEY id
name
TABLE project
PRIMARY KEY id
name
TABLE restorer2project
FOREIGN KEY restorer_id REFERENCES restorer(id),
FOREIGN KEY project_id REFERENCES project(id)
PRIMARY KEY (restorer_id, restoration_project_id)
TABLE monument2project
FOREIGN KEY monument_id REFERENCES monument(id)
FOREIGN KEY project_id REFERENCES project(id)
PRIMARY KEY (monument_id, project_id)
Project can have many restorers and have many monuments.Also project can repeat in future with same relations, but different date.
I want to create table witch will store pictures.
TABLE picture
PRIMARY KEY id
reference_to_different_tables
Is it possible point to different tables from one column?
if yes how?
Is this good design (fro me it is natural i can imagine to create more tables with pictures)
Other approach is to have references to pictures from other tables, but then i will need some kind of mapping table, but not sure if it is also good design.
From database prespective you can't have a foreign referring to different tables.
It can refer to one table at a time.
There can be three solutions I can think of:
The best solution in my opinion is to have a parent table say artifact to monument, restorer and project. The later three tables will have primary key as foreign key from artifact table. This way you can have single column in picture table which will refer to artifact table.
Or you can specify multiple columns in picture table as suggested by #CptMisery in the comments.
Create multiple picture table for all of them. This is not considered as good solution.
If you are using any persistence framework than the first solution can solve dynamic query problem as well.

Duplication entry at foreign key column

I have referenced a foreign key to a primary key. Whenever I click on create new project, I am storing the project Id in the reference key but I want to store multiple projects.
Can anyone please help?
Even your query is not much clear that what issue you are getting but you can understand foreign key concept as per below-
If you create a foreign key in any child table and referenced it with master table means you are saying that child table can contain a value only its reference exists in parent table.
Normally in mostly cases we want to use normalization and basic concept is that we keep unique value in master table (mostly primary key) and its child rows (multiple) in its child table.
Suppose we have two tables customer and order then customer table contains unique customer but as same customer can order multiple times, so order tables may contains multiple customers.
In your case whenever you will create a new project then a new project_id will insert in master i.e. project table and its multiple sub-attributes in its child tables. Now whats the issue you are facing. Please explain.