A large amount of foreign keys in mysql ? this is good? - php

Hey guys (and probably girls). I'm modelling a huge database in mysql for a company that i work and i'm stucked on things that you might help me.
My question is very simple: How do i know that a number of foreign keys is enought ?
I have 8 tables that describes the following datas:
1st relationship
table country (pais)
table state (estado)
table city (cidade)
(city => state => country)
2nd relationship
table department (departamento)
table sector (setor)
table role (cargo)
(role => sector => department)
3rd relationship
legal entity (entidade juridica)
company (empresa)
(company => legal entity)
And finally i have a ninth table called employee and this table have foreign key references of all the tables previously described.
(primary) id-colab
fone_colaborador
fax_colaborador
ativo_colaborador
email_colaborador
(primary) cargo_id_cargo (cargo table)
(primary) cargo_setor_id_setor ( cargo table)
(primary) cargo_segor_departamento_id_departamento (cargo table)
(primary) empresa_id_empresa (empresa table)
(primary) empresa_entidade_juridica_id_entidade_juridica (empresa table)
(primary) empresa_entidade_juridica_cidade_cidade_id (empresa table)
(fK) cargo table
(fk) empresa table
The main concept of this model is.
I have a register of a legal entity.
legal entity must be placed on country => state => city
I have a register of a company
Company should inform whether it is a branch or parent company
Company should have a referece to the legal entity table (that owns address, phone, state id, city id, country id, postal code and etc...)
I have a register of a role
Role should have a reference to the sector table
sector table should have a reference to the department table
And finally, the main table called employee described on the image above.
I hope you guys have undertood me !
See ya.

You can have 100 foreign keys in your table if that's what's required to keep your data properly normalized. Don't worry about the number. Worry about keeping your fields appropriately atomic and your schema normalized.

Related

how to retrieve data from sql table and insert it into another table

I am developing a 'online students discussion platform' for a certain university, i want a student to post a question to only students belonging in the same faculty so that if ICT student posts a question, the system extracts all the students in ICT faculty from the students table, attaches them to the post and inserts them into the table receivers.
The system is extracting all students from the students table but it is inserting only one student in the table receivers.
TABLES:
-students(regno,name,faculty_code) PRIMARY KEY regn
-receivers(id, regno,message_id)
how to do it?
Instead of having a table for receivers, a better approach would be for you to have a "faculty_code" field in the "message" table which would be populated with the faculty_code of the poster. So for each student, extract messages where student.faculty_code is equal to message.faculty_code.
That way a student only sees messages posted by students in the same faculty as him/her.

php mysql relational definition in tables

guys I've been trying to create create a school results management system.There is a STUDENT table and many COURSE tables. Each student must be linked to all Courses tables. e.g JOHN, MARY,PETER must partake in MATHEMATICS, ENGLISH, ELECTROPHYSICS, PROGRAMMING etc
My problem is how to define this relationship in mysql and at same time let these students fetch only their own results in all the courses.
I don't know if you have a requirement to have each course in a separate COURSE table but that doesn't make much sense. You should have a STUDENT table and a COURSES table. Then, you will need a STUDENT_COURSES table to show which courses a student has taken or must take. Your table structure should be something like:
STUDENT: Id, Name, Gender, etc
STUDENT_COURSES: Id, Student_Id, Course_Id, Taken, Grade
COURSES: Id, Course_Name
When a new student is created, you would need to add records to the STUDENT_COURSES table to insert the new STUDENT.Id into the Student_Id field and the Course_Id for each of the required courses. The default value for Taken would be false and the Grade would be Null or Empty String.
This is a very simplistic example and would not work in a real world solution because you would need to have Instructors, Locations, Etc. to make anything useful. But hopefully this will help you get started.

Correct relationship between user table(present) and employee table(past and present)

I´m creating a Mysql database where the user table is implemented for login/access purposes and i need to create an employee table with current and past employees. The current employees should have a (1 to 1)corresponding user, past employees shouldn´t. What would be the best way of doing this? Is the design correct?
Thanks
My approach would be to have an employee table with an employee_id Primary Key. This contains current and past employees. I would then have a user table with an employee_id field which has a foreign key relationship with employee.employee_id.
When employees leave the record from user can be deleted to remove their access, while keeping their record in the employee table.
You can make an attribute 'status' in employee table and assign 0 for past employees and 1 for present employees.
Take the employee_id as foreign key in Users table.
Make a join and check status at the login if the status is 1 then proceed to login.

MySQL Database: How far to Normalize / Queries VS Join / Unique Index

Lately i found myself designing a database. The database is consisted of several tables (InnoDB) :
Table 1: Country (id , country_name)
Table 2: City (id, city_name , countryid)
Table 3: Users (id , cityid , A , B, C, D, E)
On the Users table, A , B ,C , D and E are some characteristics of the user, where characteristic A if you combine it with cityid must be unique, that is why i created a unique index for these 2 columns:
CREATE UNIQUE INDEX idx_user ON Users(cityid , A);
The rest columns B,C,D and E are other user characteristics (for example hair color, height, weight, etc.), that as you understand, will be repeated on the table ( hair color = black, or weight = 75 kg).
At the same time countryid and cityid are configured as foreign keys on UPDATE and DELETE CASCADE.
Search will be based on cityid and A columns. A drop down menu to select the city (hence cityid) and a text box to insert the characteristic A and then hit SEARCH button.
My questions are:
On Users table, i have repeating data in the same column (columns B, C ,D and E). This is against 2NF. Do i have to create a separate table for each of these columns and then assign a foreign key of each of these tables to Users table in order to achieve 2NF?
Table B (id, Bchar)
Table C (id, Cchar)
Table D (id, Dchar)
Table E (id, Echar)
Users (id, cityid, A, Bid, Cid, Did, Eid)
For the time i will not use columns B,C,D and E as search data, only display them after searching using cityid and A search. If (in the future) i decide that i need to display all results of Users that live in cityid and have black hair, what do i have to keep in mind now while designing the database?
In one hand we have DML(INSERT, UPDATE, DELETE) and on the other hand quering (SELECT). DML will work faster on normalized DBs and quering on denormalized DBs. Is there a middle solution?
Will UNIQUE INDEX created above , be enough to ensure uniqueness for the combination of the data in columns cityid and A? Do i need to further restrict it using JavaScript or better PHP?
Multiple Queries VS Joins:
Normalizing the database will require multiple queries or a single query with joins. In the case where "The user searches for a user from Madrid with characteristic A":
a) Multiple queries:
i) Go to City table and find the id of Madrid (for example, id = 2 )
ii) Given the Madrid id and the input for characteristic A, go to Users table and SELECT * FROM Users WHERE cityid="2" AND A="characteristic";
b) INNER JOIN:
i) SELECT City.city_name, Users.B, Users.C FROM City INNER JOIN Users ON Users.cityid = City.id;
Which one should i prefer?
Thanks in advance.
Your tables are already in 2NF.The condition for 2NF is there should be no partial dependency.For example lets take your users table and user-id is the primary key and another primary key more appropriate to call candidate key is (cityid,A) with which you can uniquely represent a row in the table.Your table is not in 2NF if cityid or A alone is enough to uniquely retrieve B,C,D or E but in your case one needs both (cityid,A) to retrieve a unique record and hence it's already normalized.
Note:
Your tables are not in 3NF.The condition for 3NF is no transitive dependency.Let's take the users table here userid is the primary key and you can get a unique (cityid,A) pair with that and in turn you can get a unique (B,C,D,E) record with (cityid,A) obtained from userid.In short if A->B and B->C indirectly A->C which is called transitive dependency and it's present in your user table and hence it's not a suitable candidate for 3NF.

Database design for an auction style website

I'm creating an auction style website where users can bid for items. I've into a bit of confusion regarding the database design when it comes down to projects and bidding features. Initially I thought a table called 'project' could contain a multiple-valued column called 'bids' containing bid_id's.. However after a bit of research it appears this method is a no-no.. But I'm sure I can remember a lecture or two from university that mentioned multi-valued columns in database designs. What would be the best approach for the problem?
Thanks
Dan
It depends on your requirements on how to design the database. If you have exactly one auction per product ID, a BID table may be enough. If each auction requires individual configurations you may end up with an AUCTION table as well:
The product table
PRODUCT
PRODUCT_ID -- primary key
....
Auction table
AUCTION
AUCTION_ID -- PK
PRODUCT_ID -- foreign key to PRODUCT
START_TIME
END_TIME
MODE -- e.g. dutch, english...
...
Bid table
BID
BID_ID -- PK
AUCTION_ID -- foreign key to AUCTION
AMOUNT
TIME
...
In general, you should avoid multi-valued columns in a relational database model. You should aim for normalization. If it later comes to query optimization you may need to introduce further indexes, views and/or procedures.
In my opinion, the best solution would be to have a table bids containing all the necessary information in columns, for example: bid_id, product_id, bid_amount, bid_time, etc.
this is only meta-sql, you know.
users: id, ...
bids: id, auction_id, user_id, amount,
auctions: id, object, ... end-date, ...
indexes on bids: auction_id, amount desc
(among others like id's, names ...)

Categories