SQL – join 2 mysql tables and get data result from them

Posted by Shek on March 16, 2011 under MySQL | Be the First to Comment | Total View: 2,751 views

In this post, I am going to talk about how to get data from 2 mysql tables instead of 1 table with a sql.

Here are 2 mysql tables (The field types are ignored in this examples):

Table ” People”

ID name

2

3

May 

John

Peter

Table “course”:

ID name peopleID

2

3

Computing 

Art

Chemistry

1

2

Here we would like to use a SQL to display all of the course names which May has taken:

To do so, let us seperate the SQl into 3 parts:

  1. The results we want to get which is “name” from people from “name” from course.
  2. The tables we are going to search which are tables “people” and “course”
  3. The conditions of this query which is “all course taken by May”

Here is the SQL:

//part 1 the result we want to get:
select people.name, course.name
//part 2 the tables we are looking for
from people, course
//part 3 is the conditions.
where people.ID = course.peopleID
and people.name = "May";
 
//All together without comments:
select people.name, course.name
from people, course
where people.ID = course.peopleID
and people.name = "May";

With the SQL above, we will get:

May Computing
May Art

Not what you want? Try a Search

Add A Comment

*