MySQL - Represent an array - mysql

I want to create a database structure that can store data about families (primary key, name and its members).
I came up with the idea of doing it using these two tables:
TABLE "family":
- id (INT)
- name (VARCHAR)
- members (?)
TABLE "members"
- id (INT)
- name (VARCHAR)
I would like to reference members of the family by the id in the members table. But since MySQL doesn't have arrays, how am I supposed to store multiple members in one column? Or are there better DB structures for this case?
Kenta1561

Don't try to store multiple value in a single cell as arrays. It'll be nightmare for you later when you have to search rows based on one of the value in those arrays or join table with that column and other operations of the sort.
You can create a separate mapping table for that to keeps the things normalized.
You can create a separate table family_members with, say, three columns:
id (auto increment),
family_id (FK to family table),
member_id (FK to members table)
Or have an extra column in the members table as FK to family table if there is one to many mapping.
The mapping table helps if there can be many to many mappings.

Create Foreign key to Member_Id in tblFamily table
TABLE "tblFamily":
- Fam_Id (INT)
- Family_Name (VARCHAR)
- Member_Id (INT)
Create Primary key to Member_Id in tblMember
TABLE "tblMembers"
- Member_Id (INT)
- Member_Name (VARCHAR)

You can try below structure :
Table "Family"
- FAMILY_ID INT (PK)
- FAMILY_NAME VARCHAR
Now as your family can have multiple members, so instead of storing member_id in family table, it will be good to store FAMILY_ID in MEMBERS table.
Table "Member"
- MEMBER_ID INT (PK)
- MEMBER_NAME VARCHAR
- FAMILY_ID INT (FK) REFERENCES FAMILY.FAMILY_ID
This way you will be able to store multiple members for a family and using join on these tables will be able to print all information about the family in single query.

Related

Creating relationship between user, type, and type-title table

So I was trying to create a proper table relationship for user info tables, but got confused in the end.
Here is the scenario:
1. a **user** can have more than one **type**.
2. where the **type** are: founder, member, and crew.
3. for the crew type, it can have more than one **crew_title** ex: Crew Leader, PR Manager, etc.
4. and a crew-type-user can only have one **crew_title**.
These are my tables so far:
**user** table:
- user_id (PK)
- email
- password
**type** table:
- type_id (PK)
- type_name
**user_has_type** table:
- user_id (PK)
- type_id (PK)
I tried to create the crew_title inside the type table, like this:
**type** table:
- type_id (PK)
- type_name
- crew_type_title
But I don't know is that the proper way, since there will be so many empty cell, because there will be only 7-10 users who is crew. Any help would be nice:)
You can keep the relation between the user and the type_title like this:
user table:
- user_id (PK)
- email
- password
type table:
- type_id (PK)
- type_name
type_title table:
- type_title_id (PK)
- type_id
- title
user_type_title table:
- user_type_title_id (PK)
- user_id
- type_title_id
SELECT U.*, TT.TITLE
FROM USER U
LEFT JOIN USER_TYPE_TITLE UTT ON UTT.USER_ID = U.ID
LEFT JOIN TYPE_TITLE TT ON TT.TYPE_TITLE_ID = UTT.TYPE_TITLE_ID
EDIT:
So before inserting, you should detect which type title goes to which user. For example, let's say this is a dashboard screen for your app and you are setting user type titles. On your screen, you will first select a user (user_id),
SELECT * FROM USER;
and then a type,
SELECT * FROM TYPE;
and after selecting the type there will be type titles of that type. You will choose the type title from there (type_title_id).
SELECT * FROM TYPE_TITLE WHERE TYPE_ID = <selected_typeid_from_ui>;
So while inserting the same scenario:
INSERT INTO USER_TYPE_TITLE SET USER_ID = <selected_userid_from_ui>, TYPE_TITLE_ID = <selected_typetitleid_from_ui>;
I'm a little new to this.. But whenever I find that a given table I use has one too many null entries, I believe the practice used to solve it is called normalisation of the table
So how about leaving this as is
type table
type_I'd(PK)
type_name
And adding this
crew_subcategory table
-User_Id(pk)
-Crew_id(fk)
crew_title table
-Crew_Id(PK)
-crew_type title
The crew subcategory table will contain only the entries having a crew title
And the crew title table provides the respective title according to the id. This is similar to what you've used for title and title id
Not sure if this is the best approach. Let me know what you think about it :)
I thinking:
user table:
- user_id (PK)
- email
- password
type table:
- type_id (PK)
- type_name
user_has_type table:
- user_id (FK) Foreign Key
- type_id (PK)
type_title
id(PK)
title_name
title_has_type
title_id(PK)
type_id(FK) Foreign Key
title_has_user
title_id(PK)
user_id(FK) Foreign Key

Grouping many tables with similar structure but diferent meaning

I have many tables with the follow structure
id(int autoinc)
name (varchar)
for definition of productoCategory, clientType, employeePosition, etc. It is a valid aproach group all this in one table with a name like "groupings"
id (int autoinc)
name (varchar)
table (varchar) <-- here especify the table that below this info(product, client, employee)
is a valid aproach? there will be problems with the scalability?

Creating a Table in SQL, where each tuple can have mutiple values

I m try to make a Table using Create Table in SQL,
where a person can work at multiple places, and a place can have multiple person working on it,
this is what i m trying, i m sure its not correct
create table ( person char(15), place char(15), salary int)
now since a person can work in multiple places, i m confused should the tuple place has multiple values,
if yes. how do i do it
Thanks in advance
It is called a n to m relation. Use 3 tables
persons table
-------------
id int
name varchar
places table
------------
id int
name varchar
place_persons table
-------------------
place_id int
person_id int
You should create three separate tables:
"persons"
int ID (primary key, auto-increment)
varchar username
varchar email ... (all other info needed)
"places"
int ID (primary key, auto-increment)
varchar name
etc.
And the third table gives you the relationship between the two:
"person_places" (or place_persons, depends on what you like)
int ID (primary key, auto-increment)
int place_id (linked to the ID of the "places" entry)
int person_id (linked to the ID of the "persons" entry)
This way, every time a person starts working in a new place, you just add an entry to the "person_places". Same thing when they leave a place, or a place goes out of business or whatever, you just need to touch the "person_places" table.
Also, this way, one person can work in several places, just like one place can have several people working in it.
This is not normalized but it is ok to use this as you have only 3 columns and normalization will add more headache of joins and extra columns to define relationship.
suppose PersonA works in both PlaceA and PlaceB. PersonB also works in both the places but on different salaries then your data will be like this
insert into Yourtable values
('PersonA','PlaceA',1000),
('PersonA','PlaceB',2000),
('PersonB','PlaceA',1100),
('PersonB','PlaceB',1200),
('PersonC','PlaceA',1000)
and if you want to know that how many places PersonA works then you query will be
select place from YourTable where person = 'PersonA'
This way you don't need to save multiple values in same tuple.

Database Modelling when multiple entities are involved

I have three entities in a MySQL based web application - Customer, Service and Note. Each customer can have multiple notes posted by different users. Similarly a Service can also have multiple notes. I would like to store all the notes in a single table for easy retrieval. Basically, there are lots of querying than insert/update to these tables.
The following is the database schema:
Table: Customer
id - integer
name - varchar
status - varchar
Table: Service
id - integer
name - varchar
status - varchar
price - float
Table: Note
id - integer
note - text
author - integer
type - varchar
cdate - datetime
I have prepared two approaches for establishing the relationship between these tables:
Approach #1
Table: CustomerNote
id - integer
customer_id - integer (References Customer table)
note_id - integer (References Note table)
Table: ServiceNote
id - integer
service_id - integer (References Service table)
note_id - integer (References Note table)
The second approach is to modify the Note table to save the Entity Name and ID of the record. This approach doesn't use the relations mentioned in approach #1
Approach #2
Table: Note
id - integer
note - text
author - integer
type - varchar
cdate - datetime
entity - varchar (possible values are Customer and Service)
entity_id - integer (related to id in the corresponding entity)
The second approach doesn't need any extra tables, but it's not easy to enforce foreign key relationship. As I said earlier, there are more querying than insert/update. So in that case which one would be more ideal and efficient approach?
I would also like to know if there are any performance issues if we implement a strict foreign key relationship.
Second approach is better in anyways with an index added to type field.
It will be better if you can convert type to an integer filed to represent these values . like 1 for Seevice and 2 for Customent. Will be faster if you use integer. But in any case, this approach will not satisfy your enforce foreign key.

how to save marital relationship in a database

I have to save this information in a database
Person -> is married to -> Person
Where should I save that information? What is the proper design pattern should I apply here?
Thank you!
If you can only be maried to one person: 1:1
-------------
- Person -
-------------
id (key)
maried_to_id (foreign key)
If you can be maried to more than one person or want to keep track of previous mariages, n:n
-------------
- Person -
-------------
person_id (key)
-------------
- Mariage -
-------------
first_person_id (foreign key)
second_person_id (foreign key)
start_date
end_date
(also first_person_id + second_person_id + date form a unique key for mariage. You could leave out the date, but then remariages wouldnt be tracked)
Here is a hypothetical schema you can use. All people are in a single table, and each person has a unique id. Marriages are in a relationship table, with foreign keys.
PERSONS
- ID - INTEGER, PK
- FIRSTNAME - VARCHAR(20)
- LASTNAME - VARCHAR(20)
- SEX - CHAR(1)
- ... any other fields
MARRIAGES
- PERSON1_ID - INTEGER, FK
- PERSON2_ID - INTEGER, FK
- MARRIAGE_DATE - DATE
- ANULLMENT_DATE - DATE
- ... any other fields
This is a great question for teaching schema design. What seems like a simple problem can easily become quite complicated:
E.g., how to handle:
- mariages of more than two people
- different types of marriage (legal, religious, other)
- concurrent marriages
- repeat marriages
- divorce
- self-marriage (hey, it happend on Glee!)
The trick, if there is one, is to carefully think out all the permutations of what you are trying to model. Only then do you actually go ahead and model it.
I would recommend Following structure
Lets say table name is Person.
PersonId (int, Key)
MarriedTo (int,
nullable)
.....
No need to create foreign key relation ship.
This sounds like a use for a simple lookup table- the important part is having two fields, one a foreign key for Person1's ID field the other a foreign key for Person2's ID field. Any details about the marriage ( dates, whether it is still current and so on ) would also be stored in this table.
That would facilitate people having had multiple marriages, polygamous relationships and so on. If you want a simple 1:1 relationship you could just include a foreign key reference to the spouse in the person field, but it would be considerably less flexible.
You could do it with a "Spouse" column on the "Person" table which can be null (for the case of an unmarried person).
If married this holds the id of the other person, as is a foreign key.
A better solution would be a separate "Marriage" table that has at least three columns:
MarriageId
Person1Id
Person2Id
...
The person id's are foreign keys into the "Person" table, and you should make the combination of MarriageId, Person1Id and Person2Id unique to avoid adding a row where the people are swapped over.
Though it should be pointed out that both these models are quite basic and make assumptions about how many people can be in one marriage ;)