Where should the foreign reside in this scenario - mysql

I want the relationship to be like a single profile only have one address associated to it. While a single address can be from many profile. Where would I place the foreign key.
Address address_id, state, town, phone, email
Profile username, profile_pic, date_added, password

well since you want one to many relation for address table you should add a foreign key ( let's say addr_id ) to profile table.
That way one address row can be used in multiple profiles

From http://www.mysqltutorial.org/mysql-foreign-key/:
"The customers table is called parent table or referenced table, and the orders table is known as child table or referencing table.
A foreign key can be a column or a set of columns. The columns in the child table often refer to the primary key columns in the parent table."
Looks like you want the foreign key on the user table.
Hope this helps!

Related

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

MySQL, InnoDB: two-column unique constraint with one column in parent table

In a child table, I need to enforce a unique constraint with a composite key where one of the two columns is in the parent table.
The situation is that in my application users can have multiple accounts of different types. One of these types represents an account from a foreign source that has its own id (foreign_account_id), the others are internal and only have the account_id primary key. Now, different users can be connected to the same account from the foreign source, but each user only once. So i need a composite unique key over users_id and foreign_account_id.
Is that possible or is there a good workaround for this (e.g. would it be good practice to just repeat the column users_id in the child table)?
This is the structure
accounts (parent)
id (primary)
users_id
description
....
accounts_foreign (child)
accounts_id (primary, fk for accounts)
foreign_account_id
info1
info2
...

Having both primary key and foreign key in the same table

Should I both have a primary key and a foreign key in the same table?
Eg: one to one
I have a User table and a Address table.
Each User has one address.
Should I only add a foreign key in the Address table that points to the primary key in the User table?
Or should I also create a primary key in the Address table?
Update:
Each User CAN have a address. So not all users will have a address. If a user decides to enter his/hers address. Then the address will end up in the Address table
As I said in my comment, the first question is why you need an address table at all if they are truly 1 to 1?
That aside, I would reverse the relationship. You state that:
Each User has one address.
If that is an accurate description of the model, the User table should reference the address table, and not the other way around. An address could have multiple users. So the user table would have a foreign key column that points to the address table.
Regarding other comments and answers, I agree that it's a good practice for nearly every table to have a primary key. There are certainly exceptions, but it's a good rule of thumb.
I would recogmend you to use a primary key in each table. It could happen, that 2 users live in the same house. Just to be safe...
All tables should have a primary key. The foreign key points to a primary key in another table to establish the relationship.

MySQL unique constraint over two column that are in different tables

First I have one table Device that have id, account_id and name .That table has unique constraint over its two column(account_id, name) , meaning we can only have same name if account_ids are different.
Now I split it into two tables Device(id, account_id, profile_id) and Profile (id, name).
My question is how I can apply unique constraint as before. I don't allow same profile name with the same account_id. How can I do that in MySql(5.5)? I think I need unique constraint over two tables.
Is it possible?

Featured value in one to many relation, which table should hold that?

say that i have a one to many relations where there are two tables, a Person table and a Belonging table. Now, each Person has ONLY ONE favorite belonging and a specific belonging cannot belong to another person as well.
My question is, where would that information be better kept ? In the Person table as a favorite_belonging_id or in the Belonging table as an is_favorite entry ? To my eyes, the first choice seems to be the better version, but I would like to hear what sql knowledgeable people have to say about it.
EDIT : A Person has many belongings but only ONE favorite belonging and each belonging can only belong to one person. It's a one to many association.
I'd be tempted to go with your first suggestion (a favourite_belonging_id column in the Person table), as one can then create a foreign key reference from (person_id, favourite_belonging_id) to (owner_id, belonging_id) in the Belonging table.
If one were to go the other route of creating a is_favourite flag in the Belonging table, there is no obvious way of ensuring the 1:1 nature of person-favourite belonging relationships (a composite UNIQUE index over (owner_id, is_favourite) would fail when a person has multiple belongings that are not their favourite).
That said, it doesn't feel like this information really belongs in the Person table, as it isn't really a property of the person but rather it's a property of the Belonging. If you feel strongly about it, you could create a Favourites table that has a UNIQUE (or PRIMARY) index over person_id.
to me it does NOT belong in the person table since it has nothing to do with the base person.
if you have only the belonging table - which i also assume has a person_id in it, then this is where you are expressing the relationship between the belonging and the person, and it is where the qualifier should also go.
another option is to have a third table in the middle linking the two - in this case, the favorite flag goes there.
edit:
my preference in design would be the third table option - here you can put a begin date and end date as well as the favorite flag - this would allow you to theoretically trade a belonging to another person at some point in time and still know what happened.
I see that pretty much all the different options have already been laid out in different answers, but instead of commenting on all to give you my impression on what I think you should do, I'll just create an answer myself.
Just to be clear on how I understand how the system works: All users can have multiple belongings, but any belonging can only be help by one person.
In this case, it makes the most sense to have a user_id in the belongings table that can tie a belonging to a person. Once a user_id is set, nobody else can claim it anymore.
Now, as to the 'favorite' part, there are several things you can do. What truly is the best way to do it strongly depends on the queries you plan on running on it. Some consider adding a JOIN table, but honestly this is a lot of additional data that is rather pointless; there is likely going to be the exact amount of rows in it as the user table and by putting it in a separate table, there is a lot you can't do (for example, see how many people DON'T have a favorite). Likewise, a JOIN table would make no sense for the user_belonging relationship, as there is a 1:1 relationship between the belonging and the amount of people who can have it.
So I believe there are two viable options: either add a field (/switch) in the belongings table to indicate of a user's belonging is his/ her favorite, or add a field to the user table to indicate which belonging is the user's favorite. I would personally think that the latter holds the most merit, but depending on the queries you run, it might make more sense to to the former. Overall, the biggest difference is whether you want to process things pre-insert or post-select; e.g. in the latter situation, you will have to run an independent query to figure out if the user already has a favorite (in the former case this won't be necessary as you would put a unique index on the field in the user table), whereas in a post-select situation you will have to do cross reference which of the selected belongings from the belonging table is the user's favorite.
Please let me know if I explained myself clearly, or if you have any further questions.
The following may not be the best options because it offers a somewhat unconventional method of flagging the favourite belonging. The advantage, though, is that this way you'll have just two tables with no circular references and every person will be guaranteed to have no more than one favourite belonging.
So, it's two tables, people (or persons) and belongings. The people table has this structure:
person_id INT AUTO_INCREMENT,
other columns as necessary,
PRIMARY KEY (person_id)
The belongings table is created like this:
belonging_id INT AUTO_INCREMENT,
person_id INT NOT NULL,
is_favourite enum ('1'),
other columns as necessary,
PRIMARY KEY (belonging_id),
FOREIGN KEY (person_id) REFERENCING people (person_id),
UNIQUE (person_id, is_favourite)
The key element is declaring is_favourite as a nullable enum with a single possible value. This way, when you declare a unique constraint on the pair of (person_id, is_favourite), you are allowed to have as many rows with the same person_id and empty (null) is_favourite as possible, because unique constraints ignore rows where at least one member is null. And you won't be able to create more than one person_id with is_favourite = '1', because that would violate the unique constraint.
Neither. My suggestion is to add another table person_favourite_belonging, like this:
CREATE TABLE person
( person_id INTEGER NOT NULL
--- various other columns about Persons
, PRIMARY KEY (person_id)
) ;
CREATE TABLE belonging
( belonging_id INTEGER NOT NULL
, person_id INTEGER NOT NULL
--- various other columns about Belongings
, PRIMARY KEY (belonging_id)
, UNIQUE KEY (person_id, belonging_id) --- this Unique constraint is needed
, FOREIGN KEY (person_id)
REFERENCES person (person_id)
) ;
CREATE TABLE person_favourite_belonging
( person_id INTEGER NOT NULL
, belonging_id INTEGER NOT NULL
, PRIMARY KEY (person_id)
, FOREIGN KEY (person_id, belonging_id) --- for this Foreign Key constraint
REFERENCES belonging (person_id, belonging_id)
) ;
This is just my preferred way of doing this. There are alternatives and all have their pros and cons. The pros with this approach are:
No circular path in the Foreign Key constraints (and therefore):
No chicken and egg problems when inserting, deleting or updating Persons, Belongings or Favourite Belongings.
All foreign key columns can be defined as NOT NULL.
The integrity can be enforced at the database level.
If your requirements change and you want to have 2 (or more) favourites per person, you only change appropriately the constraints at the Favourite table.
Check also my answer in this question (with an almost identical problem): In SQL, is it OK for two tables to refer to each other?
favourite_thing is a FK to the belonging table (if that table exists, otherwise it could be a domain) , but in an additional constraint, you can force belonging_id in the persons table to be unique.
UPDATE:
DROP table belonging;
CREATE table belonging
( id INTEGER PRIMARY KEY
, description varchar
);
DROP table person;
CREATE table person
( id INTEGER PRIMARY KEY
, description varchar
, favourite_thing INTEGER REFERENCES belonging (id)
);
-- Now add the unique constraint
-- NOTE: favourite_thing can still be NULL
ALTER TABLE person
ADD CONSTRAINT must_be_unique UNIQUE (favourite_thing)
;
UPDATE 2: if every belonging belongs to exactly one person, you could add an owner field to belongings:
CREATE table belonging
( id INTEGER PRIMARY KEY
, owner_id INTEGER NOT NULL REFERENCES person(id)
, description varchar
);
DROP table person CASCADE;
CREATE table person
( id INTEGER PRIMARY KEY
, description varchar
, favourite_thing INTEGER REFERENCES belonging (id)
);
ALTER TABLE person
ADD CONSTRAINT must_be_unique UNIQUE (favourite_thing)
;
Actually you present a one-to-one relation.
So you can:
1. Hold it in Person table.
2. Hold it in Belonging table.
3. Hold it in both.
4. Hold it in separate table.