Sql Foreign Key Constraint Problems - mysql

Supposed there is table called 'Bill', In the Bill Table, there are 3 columns , ['id', 'client_id', ' client_contact_id'], only 'client_contact_id' is nullable.
The client_id will foreign to the table of 'client', and in the table of 'client_contact',
there are 3 columns such that ['id','name','client_id']. How do i supposed to make a integrity of these tables to make sure the data inserted in table 'bill' with 'client_id' is same as the client_contact_id of client_id.
I want to make integrity of bill.client_contact.client_id is same as bill.client_id in mysql.
I have to mentioned that the Client : Bill are 1:n , Client :Client_contact are 1:n also. Client_contact : Bill are 1:n

Use a foreign key constraint with two columns:
foreign key (client_id, client_contact_id) references client_contacts(client_id, id)
You will need a unique index/constraint on those columns:
create unique index client_contacts_2 on client_contacts(client_id, id);
This is a bit redundant, but solves your problem without using triggers or stored procedures. It also allows NULL values. These should be ignored for foreign key relationships.

If you cannot have bills without a contract, then I suggest you remove client id from the bills table.
If you can have bills without a contract, then you need to create before insert and before update triggers on the bills table. These triggers pull the client if from the client contact table if the client_contact_id field in the inserted / updated record is not null. Alternatively, you need to handle this in your application logic.

Related

Is table order imporant in mysql when creating relation between them?

I have quite simple question. I am creating database administration tool, where user will be able to create relations between tables, but I am not sure if table order is important when creating relations.
For example: I have two tables 'user'(user_id(INT, PRIMARY KEY), name(VARCHAR), email(VARCHAR)) and 'post'(post_id(INT, PRIMARY KEY), content(TEXT), author(INT)).
When user has selected one column from both tables ('user'(user_id) and 'post'(author)) tool creates a query:
ALTER TABLE 'user' ADD CONSTRAINT 'user_id_to_author' FOREIGN KEY ('user_id') REFERENCES post('author')
but if user would select tables in different order ('post'(author) and 'user'(user_id)) then query would look like this:
ALTER TABLE 'post' ADD CONSTRAINT 'author_to_user_id' FOREIGN KEY ('author') REFERENCES user('user_id')
Is there any difference between both query's and if so whats is it?
You are defining a one-to-many relationship, so the direction of the relationship does matter.
The table that is altered is the child table; many rows may refer to the parent table, through the primary key of the parent table.
For the example given here, a post belongs to a user, and many posts may have the same author, so you want:
ALTER TABLE post
ADD CONSTRAINT author_to_user_id
FOREIGN KEY (author) REFERENCES user(user_id)
Note that object names should not be surrounded with single quotes.
Trying to create the relationship the other way around does not make sense. It would imply that a user needs to have a post before it can be created.

In a one to one or one to many relationship in a database, which table must have the foreign key?

Sorry If my question seems too obvious but I still can't find the logic between a relationship of a database model.
ONE TO ONE:
If I have a customer that has only one address where do I have to put my foreign key ?
I first thought it would be a good idea to put it on the customer's table; one column with a foreign key referring to an id of an address.
Because if I need to create a customer, first I would need to create an address.
But I have found some example on the internet
, where they put a foreign key in the address' table, referring to an id of a customer
ONE TO MANY :
And the same question would apply if a customer can have multiple addresses, in which table, should I put my foreign key ?
The foreign key goes on the "many" side.
For example, if a sales_order is associated with at most one customer, and a customer can have zero, one or more sales_order
Then we put customer_id in the sales_order table, as a reference to the (unique) id column in customer table.
This means that we will first need to add a row to customer before we can add a sales_order for that customer. (The foreign key constraint will prevent us from adding a row in sales_order that has a value in customer_id column that doesn't exist in id column of customer.
--
For the special case of a one-to-one relationship, we can implement that the same way as a one-to-many, with an additional UNIQUE constraint on the foreign key column. It really comes down to deciding which direction of the relationship is mandatory, and which is optional. Basically, which table will we add a row to first? The table where we add rows later will have the foreign key constraint referencing the table that we previously added a row...

Am I supposed to use foreign keys for these 3 tables which are connected?

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).

MySQL Foreign Keys + which table to put the key on

I just starting to use Foreign Keys to enforce the contents of certain Columns and want to be sure I'm putting the Key on the correct table.
In a situation with 2 tables that have a one to many relationship.
e.g.: customers (one) and orders (many).
Where I want to ensure a valid customer number is used in an orders column.
I'm I correct in saying the Foreign Key would placed on the orders table.
e.g.: orders (columnX) references customers (columnX)
Remember that a foreign key is a referential constraint that says the range of values in a table column(s) is being scoped by another table. Specifically, for your example, you would have a customer_id column in your order table that would be a foreign key back to the customer table, meaning that the in all cases you need a valid customer id in order to insert a record in the order table.
Yes, the primary key (typically a customer id) on the one table (customers) should be linked as a foreign key on the many table (orders) in a one-to-many relationship. Each order can belong to only one customer, but a customer can place many orders.

Having two foreign keys into a single column

I have a problem in creating a table with a column that has two foreign Key relationships. Let me explain in detail.
I have three tables:
Table A - columns ID (primary key), Name
Table B - columns ID (primary key), Name
Table C - columns ID, Name, Detail
In C.Detail I have to store data from both other tables (A.ID & B.ID). So I tried to add two foreign key into the column C.Detail. During insert operation in Table B the following error occurs, and the same error message occurs while trying to insert data into Table A.
"The INSERT statement conflicted with the FOREIGN KEY constraint
"FK_C_A". The conflict occurred in database "X", table "dbo.A", column
A.ID."
Please, can anyone help us to rectify this problem? We don't want to add two columns in table C for two foreign keys.
Hopefully waiting for the reply.
I will suggest to introduce two new columns in Table C. (i.e AID and BID).
Create Foregin key on this news columns.
I could be wrong, but I think the way to go about doing this is to create a "parent" table for A and B that has A_B_parent.id(primary_key) and then have A and B both have foreign keys on their id to the parent table. Then C can also have a foreign key to the parent table.
This obviously ends up being really complex, so the better solution might just be to programmatically enforce the constraint rather than using foreign keys and then put a comment on the table.