To get 2 primary keys from different tables in mysql - php

I'm doing my final year project and planning to do comment feature on my system. The customer that have purchased the meal only can comment or give feedback about that particular meal. So, I need to get the Meal_ID and Cust_ID from table 1 and table 2 in order to keep track who's comment on what meal. I just want to ask is it possible to select multiple primary keys from different tables in one sql query? Thanks in advance!
I have 3 table as shown below.

Foreign Key:
Example:
CREATE TABLE Orders
(
O_Id int NOT NULL,
OrderNo int NOT NULL,
P_Id int,
PRIMARY KEY (O_Id),
FOREIGN KEY (P_Id) REFERENCES Persons(P_Id)
)
Description: The following SQL creates a FOREIGN KEY on the "P_Id" column when the "Orders" table is created:
Fetching Data:
Ya it it possible to select two Primary keys from a single select statement with the help of JOIN Query so that you can combine both the tables and you can get the result with the help of single query.
There are different types of Join available and you can use any such method:
JOIN
Left JOIN
Right JOIN

Related

i have three columns, i want to combine them all in one main_table

i am working in mysql, i know about tables relationships 'joins' etc,
I have three different tables, each table has column id, i want to combine all three ids in one main table, because i want to apply inner join after getting all ids in one table.
can you please tell me how i can get all three ids in one table, i know about foreign key and primary key, but i don't know how i can apply that here... or is there any simple method of doing it.
My tables name:
Table 1 contains: student_id coloumn
Table 2 contains: teachers_id
Table 3 contains: class_id
Main table is table 4: which will have student_id,teachers_id,class_id coloumn
i am trying to generate time table, i want get student id,teachers_id and class_id, in main table time_table; i am trying to do normalization so that i don't have to repeat all name again and again, i can just use id to call any class name teacher name subject name etc, all ids are primary keys in tables.
The relationship is one to one in this case
i am working on php_mysql.
Thankyou
Create tables as follows,
create table subject(subject_id int primary key,sub_name varchar(20))
create table teacher(teacher_id int primary key,teacher_name varchar(20))
create table class(class_id int primary key,class_sec varchar(20))
create table timetable(t_id int primary key,subject_id int references
subject(subject_id)
,teacher_id int references teacher(teacher_id),class_id int references
class(class_id))
Inserting sample values
insert into subject values(1,'Tamil')
insert into teacher values(1,'Pugal')
insert into class values(1,'12th A')
insert into timetable values(1,1,1,1)
Using Inner join to connect tables,
select s.sub_name,t.teacher_name,c.class_sec from timetable t1
inner join subject s
on s.subject_id = t1.subject_id inner join teacher t
on t.teacher_id = t1.teacher_id inner join class c
on c.class_id = t1.class_id
Try this...And revert me if any clarifications needed..
SELECT Teachers.teacher_name, Class.class_sec, Subjects.subject_name FROM timetable
INNER JOIN Teachers ON Teachers.teacher_id = timetable.teacher_id
INNER JOIN Class ON Class.class_id = timetable.class_id
INNER JOIN Subjects ON Subjects.subject_id = timetable.subject_id
As I understand it, and please correct me if I am wrong,
A class has a teacher, simplifying, a teacher teaches one class or more(the more complex case is more than once teacher per class):
The relation is 1 to many, so the class table should hold a teacher_id
A student can take more than one class, but there are many students in a class, then relationship is many-to-many,
a new table should be created class_per_student
We need to populate them with the relevant info of course,
Once that is done, we can join all relevant tables and get the timetables
Add the teacher_id column:
ALTER TABLE class ADD COLUMN teacher_id INT(9) NOT NULL;
ALTER TABLE class ADD KEY teacher_id (teacher_id);
Create a many-to-many table
CREATE TABLE class_per_student (
id INT(11) NOT NULL AUTO_INCREMENT,
class_id INT(9) NOT NULL,
student_id INT(9) NOT NULL,
PRIMARY KEY id (id),
KEY class_id (class_id),
KEY student_id (student_id)
);
The time table select:
SELECT
cps.class_id,
cps.student_id,
c.teacher_id
FROM
class_per_student cps
INNER JOIN class c ON c.id = cps.class_d
;
Notice that since the relationship between all entities is many-to-many, each of them (class, teacher, student) will appear more than once, BUT the unique combination of the 3 will appear once

MySQL relationship database design

I have seen a question on this forum that I can relate with, but I can't apply the answers to my question.
Here it goes:
I have a memberlist table (id, name, number) I'll just make the columns short.
Next, I have an events table (id, eventName, description)
Now,
1. each member in the memberlist can join events as many as he wants.
2. each events in the events table can have members without limits (okay, say 1k members, like that or whatever).
What I have now is an event table that has a column named: "joiners" which will contain the id of a certain joiner/member. But I believe I'm wrong because how can a certain event handles many joiner's id?
I would rename memberlist into members to make your table naming more consistent. Or events into eventlist. Which ever you like more.
Then you want to define a many to many relation between members and events. This is done through an intermediate table which will reference both:
create table eventmembers (
id int unsigned not null primary_key auto_increment,
member_id int unsigned not null references members(id),
event_id int unsigned not null references events(id)
)
I'm assuming that on your memebers and events you already have id fields which are set to be primary keys.
If you want to get all events attended by a specific user you can then do
select events.*
from events
left join eventmembers
on events.id = eventmembers.event_id
where
member_id = ?
and get all the members in an event:
select members.*
from members
left join eventmembers
on members.id = eventmembers.member_id
where
event_id = ?
You'd want a third table called events_memberlist :
events_memberlist
- memberlistId
- eventId
This would allow you to maintain a many-to-many relationship between the two tables.
you need a third table for fun we will call it EventMemberTable, col's:
event id | member
it links the appropiat member to the appropiat event. Keeping your other tables clear of redundant data.
You can achieve this by having a middle table (between members, and events). Middle tables are necessary in situations where a 'many-to-many' relationship between two tables is required.
In the middle table, you will include the primary keys of both tables as foreign keys, on the same row, when a member has joined an event. The foreign keys effectively create the relationship between one member, and one event. The table however, can have thousands of these entries.
I hope that helps.
P.S. Maybe post some syntax next time.
Cheers
When you use a middle table as already mentioned like:
CREATE TABLE event_members (
member_id INT UNSIGNED NOT NULL REFERENCES members(id),
event_id INT UNSIGNED NOT NULL REFERENCES events(id)
)
you should also set up a unique index to prevent multiple entries for the same member/event combination like
ALTER TABLE event_members ADD UNIQUE INDEX uniq_event_members_idx (member_id, event_id);
Otherwise you might end up with loads of duplicates.

Inserting "large" amounts of data into MySQL and the benefits of using a foreign key

I'm not sure how to store or insert this data. I am using PHP and MySQL.
Let's say we're trying to keep track of people who enter marathons (like jogging or whatever). So far, I have a Person table that has all my person information. Each person happens to be associated with a unique varchar(40) key. There is a table for the marathon information (Marathon). I receive the person data in an CSV that as about 130,000 rows and import that into the database.
So - now the question is... how do I deal with that association between Person and Marathon? For each Marathon, I get a huge list of participants (by that unique varchar key) that I need to import. So... If I go the foreign key route, it seems like the insert would be very heavy and cumbersome to look up the appropriate foreign key for the person. I'm not even sure how I would write that insert... I guess it would look like this:
insert into person_marathon
select p.person_id, m.marathon_id
from ( select 'person_a' as p_name, 'marathon_a' as m_name union
select 'person_b' as p_name, 'marathon_a' as m_name )
as imported_marathon_person_list
join person p
on p.person_name = imported_marathon_person_list.p_name
join marathon m
on m.marathon_name = imported_marathon_person_list.m_name
There are not a lot of marathons to deal with at one time. There a lot of people, though.
--> Should I even give the person an ID and require all the foreign keys? or just use the unique varchar(40) as the true table key? But then I would have to join tables on a varchar and that's bad. A marathon can have anywhere from 1k to 30k participants.
--> Or, I could select the person info and the marathon info from the database and join it with the marathon_person data in PHP before I send it over to MySQL.
--> Or, I guess, maybe make a temporary table, then join in the db, then insert (through PHP)? It's been already strongly suggested that I do not use temporary tables ever (this is a work thing and this isn't my database).
Edit: I am not sure on what schema to use because I'm not sure if I should be using foreign keys or not (purpose of this whole post is to answer that question) but the basic design would be something like...
create table person (
person_id int unisgned auto_incrememnt,
person_key varchar(40) not null,
primary key (person_id),
constraint uc_person_key unique (person_key)
)
create table marathon (
marathon_id int unisgned auto_incrememnt,
marathon_name varchar(60) not null,
primary key (marathon_id)
)
create table person_marathon (
person_marathon_id int unsigned auto_increment,
person_id int unsigned,
marathon_id int unsigned,
primary key (person_marathon_id),
constraint uc_person_marathon unique (person_id, marathon_id),
foreign key person_id references person (person_id),
foreign key marathon_id references marathon (marathon_id)
)
I'm going to repeat the actual question really quick.... If I choose to use a foreign key for person, how do I import all the person_marathon data with the person_id in an efficient way? The insert statement I included above is my best guess....
The person data comes in a CSV of about 130,000 rows so that is a straight import into the person table. The person data comes with a unique varchar(40) for each person.
The person_marathon data comes in a CSV for each marathon, as a list of 1,000 to 30,000 unique varchar(40)'s that represent each person who participated in that marathon.
Summary: I am using PHP. So what is the best way to write the insert/import of the person_marathon data if I am using foreign keys? Would I have to do it like the insert statement above or is there a better way?
This is a many-to-many relationship, one person can enter many marathons, one marathon can be entered by many persons. You need additional table in your data model to track this relation, for example:
CREATE TABLE persons_marathons(
personID int FOREIGN KEY REFERENCES Persons(P_Id),
marathonID int FOREIGN KEY REFERENCES Marathons(M_Id)
)
This table uses foreign key constraints. The foreign key constraint prevents from inserting bad data (for example you cannot insert a row with personID = 123 when there is no such id in Persons table), it prevents also from deletes that would destroy a link between tables (for example you cannot delete a person X when exists a record in person_marathon table witth such personID).
If this table contains the following rows:
personID | MarathonID
----------+-----------
2 | 3
3 | 3
2 | 8
3 | 8
it means that persons 2 and 3 both entered marathons 3 and 8

New table or field with array in field (php/mysql)

I need to store multiple id's in either a field in the table or add another table to store the id's in.
Each member will basically have favourite articles. Each article has an id which is stored when the user clicks on a Add to favourites button.
My question is:
Do I create a field and in this field add the multiple id's or do I create a table to add those id's?
What is the best way to do this?
This is a many-to-many relationship, you need an additional table storing pairs of user_id and article_id (primary keys of user and article tables, respectively).
You should create a new table instead of having comma seperated values in a single column.
Keep your database normalized.
You create a separate table, this is how things work in a relational database. The other solution (comma separated list of ids in one column) will lead to an unmaintainable database. For example, what if you want to know how many times an article was favorited? You cannot write queries on a column like this.
Your table will need to store the user's id and the article's id - these refer to the primary keys of the corresponding tables. For querying, you can either use JOINs or nested SELECT queries.
As lafor already pointed out this is a many-to-many relationship and you'll end up with three tables: user, article, and favorite:
CREATE TABLE user(
id INT NOT NULL,
...
PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE article (
id INT NOT NULL,
...
PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE favorite (
userID INT NOT NULL,
articleID INT NOT NULL,
FOREIGN KEY (userID) REFERENCES user(id) ON DELETE CASCADE,
FOREIGN KEY (articleID) REFERENCES article(id) ON DELETE CASCADE,
PRIMARY KEY (userID, articleID)
) ENGINE=INNODB;
If you then want to select all user's favorite articles you use a JOIN:
SELECT * FROM favorite f JOIN article a ON f.articleID = a.id WHERE f.userID = ?
If you want to know why you should use this schema, I recommend reading about database normilization. With multiple IDs in a single field you would even violate the first normal form and thus land in a world of pain...

PHP MySQL add another row function

I am starting to learn PHP;
i have two tables in my database:
the Brands List that contains Brand_ID, Brand_Name, and
Brand_Description.
the Product Lines List that contains Line_ID, Line_Name.
i want to create a third table named Offered Products that contains Offer_Id, Brand_ID, Line_Name - how can i manage this using Foreign Keys?
After creating the table, i want to create a php page that will let users to populate the third table by
Selecting a brand from a dropdown list
Selecting a Line Name from a drop down List
Beside it has a button "Add Row" - which when click will display
another row below the first one in order to do number 1 and 2 again
and so on
A save button is also present which when clicked will finally save
the record on my database.
how can i exactlydo this? please help
Creating the table.
Your third table would only need to store Line_ID and Brand_ID and (for whatever reason) you also want Offer_ID.
CREATE TABLE `Offered Products` (
/* define columns */
Offer_ID INT NOT NULL AUTO_INCREMENT,
Brand_ID INT NOT NULL,
Line_ID INT NOT NULL,
/* define primary key */
PRIMARY KEY (Offer_ID)
/* define foreign keys */
FOREIGN KEY Brand_ID (Brand_ID)
REFERENCES `Brands List` (Brand_ID)
FOREIGN KEY Line_ID (Line_ID)
REFERENCES `Lines List` (Line_ID)
);
This assumes that the Lines List table (with a space) and Brand List table have Line_ID and Brand_ID respectively defined as primary keys.
Creating the form.
Design the form with HTML and PHP. Have each list populated from the corresponding table. I'm not going to provide code for this; it should be straight forward.
Inserting into the table.
INSERT INTO `Offered Products` (Brand_ID, Line_ID) VALUES (###, ###)
The ### represents the ID numbers from the HTML form.
Joining the tables.
To obtain information from all of the tables you can join as below.
SELECT * FROM `Offered Products` as op
JOIN `Brand List` as bl ON bl.Brand_ID = op.Brand_ID
JOIN `Line List` as ll on ll.Line_ID = op.Line_ID
Other Notes.
To use foreign keys in MySQL you need to be using the InnoDB engine. Using myisam will not allow foreign keys, but you can still join the tables as demonstrated to achieve a similar result.
Avoid using spaces in your table names if you actually did that.

Categories