简体   繁体   中英

How to Get Data From Two Tables - PHP and MySQL

I have two tables in MySQL as below:

Table1 as below:

ID (Primary Key Auto Increment) | Student Name | Age

Table2 as below:

Teacher Name | Student ID (This is the Student ID from table1) | Email | Education

Now I want to get data from both the tables table1 and table2 in a single query.

I want to retrieve the values from both tables where Student ID is equals to something.

Student Name | Age | Teacher Name

Can you please let me know how can I query values from two tables as mentioned above. I have read many tutorials but I can not retrieve it properly. I am new to MySQL so please explain clearly. What should I use table join, union, inner or outer join?

If there is no relationship between the tables eg. primary foreign key you should make two separate queries.

If you want to use a join you will need to create the relationship between the tables. Eg a course ID that would link the teachers table to the students table.

That way you could say show me the student and teacher names/ages from course X

Try this tutorial here .

You should implement relation by using foreign keys in your tables.

UPDATED You query should be something like this:

SELECT t1.StudentName, t1.Age, t2.TeacherName
FROM table1 t1, table2 t2
WHERE t1.id = t2.studentid;

Suppose you have table like Student(Stud_id,Stud_Name,Stud_Age) and another table like Teacher(TeacherName,StudentID,Email,....). Here StdentID should be the foreign key in Teacher, And Stud_Id Should primary key in Student.We are assuming the StudentID and Stud_ID values are same

Then try this,

SELECT Stud_Name, Stud_Age ,TeacherName FROM Student INNER JOIN Teacher ON Stud_id = StudentID

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM