I want to make three tables i.e Provinces, Languages, and Cities.
My Provinces and Cities use Languages. So I made join tables i.e Provinces_Languages and Cities_Languages. All tables contains id and name as columns.
Provinces
id
name
Languages
id
name
Provinces_Languages
province_id
languages_id
Foreign Keys
Similarly for cities:
Cities
id
name
Using same Languages Table
Cities_Languages
cities_id
languages_id
Foreign Keys
However, it can't use the same primary key from language the table. I am getting this error:
How i can resolve this?
Thanks in advance
You already have a constraint called FK_Language. Use a different name
FK_Language exists already when you try to create it again.
You should create separate alter table statements, making sure that the FK get's dropped before you create it again.
Basically: You try to drop the FK and create it again at the same time, that won't work.
By the way, you should be consistent on whether to use Cities_Languages or langauges_cities.
Related
As an introductory project for my school subject, I was requested to create an app for showing the list of shops in my country with the possibility to sort it by location and category. What is more, it should not be just a static text, as a user may add his/her own shops to the list.
Although I am not experiencing any problems with the UI and functionality of my Java application, I am a complete newbie to databases and, particularly, to MySQL. Even though I have scrutinized some tutorials, I still keep toiling over one indeed primitive issue.
The problem is:
I created a table "Shop" with columns "id"(the primary key with auto increment), "name"(text type), "type"(text type) and "location"(text type).
Alike, two more tables were made:
1) "Types" which contains "id" again as the primary key and "type". For example:
id type
1 supermarket
2 grocery
3 bookshop
2) "Location" with "id" too and "city". Something like this:
id city
1 London
2 Nottingham
3 Southampton
What I attempted to do is to create "many to 1" relation between "Types"/"Location" and "Shop" tables (or "1 to 1" between "Types" and "Shop" as well as "Location" and "Shop"), because further I would want to sort shops by location and type and, consequently, print list of relevant shops in my app. However, I simply cannot find the logical sequence how to implement those connections.
Looking forward to any tips.
Thanks in advance!
Both of the relationships you describe here are one-to-many:
A shop has one and only one type. A type can be used in many different shops.
A shop has one and only one location. A location can be used in many different shops.
An extra consideration can be made about if you allow a shop to have an empty type or location. For simplicity, we will consider that is not happening here (but it can be implemented by using nullable foreign keys).
One-to-many relationships are implemented by adding a foreign key between the two involved tables. That is made by adding a column in the child table that contains the id (primary key) of the parent table, and creating a foreign key constraint for those columns.
That is, you have to add a typeId column to your Shop table, and define the foreign key constraint in your database. Same for the relationship with locations: add a locationId column to Shop and a foreign key constraint.
You shouldn't include in your Shop table the text columns for location and type names, only the columns for the IDs. When using that information to search you will do queries with joins between the different related tables. Something lke this:
SELECT s.name, t.type, l.city
FROM Shop s
INNER JOIN Types t ON s.typeId = t.id
INNER JOIN Location l ON s.locationId = l.id
WHERE t.type = 'supermarket'
More info about joins here.
The SQL needed for implementing the foreign keys is different if you are creating the tables with the foreign keys already, or if you are modifying your existing tables. This page contains examples of both approaches.
The simple case of creating the table with the foreign keys:
CREATE TABLE Shop (
id int NOT NULL,
name text NOT NULL,
typeId int NOT NULL,
locationId int NOT NULL,
PRIMARY KEY (id),
CONSTRAINT FK_TypeShop FOREIGN KEY (typeId)
REFERENCES Types(id),
CONSTRAINT FK_LocationShop FOREIGN KEY (locationId)
REFERENCES Location(id)
) ENGINE=INNODB;
An important remark: in MySql only the InnoDB storage engine supports foreign keys, so you must create your tables with that ENGINE=INNODB parameter at the end of the SQL command in order to use foreign key constraints. If you don't specify that then the default engine will be used instead of INNODB and your foreign keys will not work. Update: since version 5.5.5 InnoDB is the default engine, so unless the engine has been explicitly changed for your database you don't need the explicit engine parameter.
This page contains a good explanation of foreign keys in MySQL (perhaps too detailed for what you need now, but you can check it for specific information).
As a best practice, name all your tables either in plural or either in singular, but use the same criteria for all. Probably you should rename table Types to Type (or either rename the other two tables to give them plural names).
So I have 3 tables:
Table: Albums
Columns: Id, Name, Description, Author, Folderpath, Thumbnail, Upvotes, Downvotes
Table: AlbumsConnection
Columns: Id, AlbumId, AlbumImagesId
Table: AlbumImages
Columns: Id, InAlbum, Imagepath
So far I've been using these tables without actually using foreign keys. Am I supposed to use foreign keys here? I understand that I'd have to add 2 foreign keys to AlbumsConnection, 1 for each table and each foreign key will reference to the primary keys ( which are the ids ) of the other 2 tables. Is that correct?
Foreign keys help ensure relational integrity of the database. There is no requirement for declaring them explicitly, but it is a good idea, particularly if you are learning to use databases.
The foreign key let's the database know that a column in one table is related to a column in another table. I don't think MySQL's optimizer uses this information explicitly, although it does create an index on the foreign key column (unlike most other databases).
In addition, a declared foreign key relationship can help you deal with changes to the database. It will prevent invalid albums from being inserted into the junction table. If you delete an album, it gives you control over how the deletion and updating is handled (via cascading constraints).
I am trying to create a database for work. I have two different types of users: internal and external. Each type has different properties so I just created two separate tables for them. In my internal table I have the following fields:
f_name VARCHAR(32),
l_name VARCHAR(32),
empl_status_id INT,
admin_grp_id INT,
reliab_status_id INT,
supv_id INT
And my external table has the following:
f_name VARCHAR(32),
l_name VARCHAR(32),
email VARCHAR(32),
phone VARCHAR(20),
org_id INT,
supv_id INT
I realize that I could probably create a separate table that contains the names of the users and a foreign key pointing to either internal or external, but that aside, I added a foreign key constraint to my internal table that refers supv_id to another internal user. I called it fk_supv_id. When I tried to do the same for my external user table, I got ERROR 1005 (HY000).
At first I couldn't figure out what the problem was but when I tried doing it with a different name, it worked (i.e. instead of calling it fk_supv_id just like for internal, I called it fk_xtsupv_id).
So my question is, what is the correct way to this? It's the same foreign key in two different tables. In both cases it refers to an internal user. Is there a way to do this without having two different names? Or should I opt for the table of names idea and add the supv_id constraint to that table along with f_name, l_name, and user_type?
Advice and suggestions are appreciated,
Thanks! :)
There are columns and there are foreign keys (FKs) and there are constraints.
You can have a column name in a table regardless of other tables.
A FK is a referencing table and column set and a referenced table and column set. All the names together identify a FK. It's a conceptual thing about a database.
A FK constraint, being a constraint, is a thing whose name must be unique over the database. It has and enforces an associated FK, namely the one described in its declaration. You can have multiple FK constraints in a table enforcing the same FK.
The DBMS has automatic unique names for FK constraints. Eg a name part plus a number part where the constraint is the numberth FK constraint of the table with that name. You can actually have the same nameless FK constraint definition text multiple times in a table and in multiple tables, each for a different FK constraint. (The ones inside a given table enforce the same FK.)
You should have a unique naming scheme for when you want to name them. Referencing and referenced table names should be involved, and when necessary distinguishing column names.
Confusingly, we say FK when we mean FK constraint.
When you say "It's the same foreign key in two different tables," that misuses terms. There are two different FKs involved, and corresponding FK constraints. You mean maybe "it's the same referencing columns and referenced table and columns in both FK constraints" or "it's the same text re referencing in both table declarations' FK constraint declarations". But the FK constraint names must be unique.
When you say "In both cases it refers to an internal user," you are confirming that the type and/or table of the referenced column are the same for both FK constraints. But they are different FK constraints for different FKs.
Names of FKs have to be unique. You need to use two different FK names. I would further suggest that you should include information about the tables being linked in the key name to make it more descriptive.
I'm trying to understand relationships and naturally questions appear.
What does referencing table mean and what does referenced table mean? In the above example which one should be referenced and which one referencing?
Lets say for the sake of argument that the settlements table is a child table (settlement cannot exist without a country). Should this child table be referencing or referenced?
I prefer not to open a new question for such a little question:
What does that Mandatory checkbox mean? Does it mean that the settlements table is required or that country_id is required? Or maybe something else?
Found a really good explanation in the PostgreSQL documentation.
Say you have the product table that we have used several times already:
CREATE TABLE products (
product_no integer PRIMARY KEY,
name text,
price numeric
);
Let's also assume you have a table storing orders of those products. We want to ensure that the orders table only contains orders of products that actually exist. So we define a foreign key constraint in the orders table that references the products table:
CREATE TABLE orders (
order_id integer PRIMARY KEY,
product_no integer REFERENCES products (product_no),
quantity integer
);
Now it is impossible to create orders with product_no entries that do not appear in the products table.
We say that in this situation the orders table is the referencing table and the products table is the referenced table. Similarly, there are referencing and referenced columns.
The referenced table is the 'parent' table.
The referencing table is the 'child' table.
The clue is in the SQL DDL e.g.
ALTER TABLE Settlements ADD
FOREIGN KEY (country_id)
REFERENCES Countries (id);
Settlements references Countries, implies Countries is referenced.
settlements table (with the country_id field) is referencing to countries table (the id field)
I suppose mandatory checkbox has nothing to do with the relation. It is simply a not null constraint on the field. But you should consult the user manual of MySQL Workbench on this one.
The Mandatory check box, if it seems to have no effect in generated SQL, has some effect on the graphic. If unchecked, you can see little circle at concerned relation line extremity (for Relationship notation crow's foot).
It means that the foreign key could be null, aka. not mandatory.
One country can have many settlements so the country table is the referenced table and the settlement table is the referencing table. I don't know about mandatory field.
I am designing a data model for tourism-site. I have a table for places (countries, resorts, hotels) and a table for tours. The tables are pretty different in fields so the cant be merged into one. Both of them have usual auto_increment as id. Places and tours have photos so there is a third table for photos. This table has 'parent' field in which I plan to store the parent (place or tour) id.
Which is the best way to design these tables? One table for all photos and two tables as 'parents' for the photos. For now I have added 'parent_type' column to photos table, so when my script displays a tour it calls photos by its (parent) id and type (parent_type) 'tour' from the photos table...
Upd:
Is there a more graceful solution? With just 3 tables and no 'parent_type' column?
(cant post a diagram... here's the link http://share.xmind.net/yentsun/tourism-site-data-model/)
Country, hotel and resort are sub-type of a place. The place table contains all fields common to places, while country, hotel and resort tables contain fields specific to each one. One tour contains many places, one place can be a part of many tours.
Here is example code for Place and Country -- it is T-SQL, but you'll get the idea.
CREATE TABLE Place
(
PlaceID int NOT NULL ,
Type varchar(2)
);
ALTER TABLE Place
ADD CONSTRAINT PK_Place PRIMARY KEY CLUSTERED (PlaceID ASC)
;
ALTER TABLE Place
ADD CONSTRAINT FK1_Place FOREIGN KEY (ParentID) REFERENCES Place(PlaceID)
;
CREATE TABLE Country
(
PlaceID int NOT NULL
);
ALTER TABLE Country
ADD CONSTRAINT PK_Country PRIMARY KEY CLUSTERED (PlaceID ASC)
;
ALTER TABLE Country
ADD CONSTRAINT FK1_Country FOREIGN KEY (PlaceID) REFERENCES Place(PlaceID)
ON DELETE CASCADE
ON UPDATE CASCADE
;
UPDATE after comment
Sorry, four tables is my best for this one.
There are no Parents involved - you just have photos with two atttributes - Place and Tour.
So use a Photos table with two foreign keys, one for Tour, the other for Place. And then of course
a Tours table and a Places table.
If you need to know which Tours went to which Places, deal with it directly with a Tour_Places table
which justifies itself independently.
As for "Parentness", this solution still lets you identify, for a Tour (or Place), which Photos are associated.
I had the same situation a while ago. I used a 'set' type for the parent_type. Never store names for your type, use integers because they can be read much faster. And also place indexes on your foreign keys.