149

I have three tables named

**Student Table**
-------------
id    name
-------------
1     ali
2     ahmed
3     john
4     king

**Course Table**
-------------
id    name
-------------
1     physic
2     maths
3     computer
4     chemistry

**Bridge**
-------------
sid    cid
-------------
1     1
1     2
1     3
1     4
2     1
2     2
3     3
3     4
4     1
4     2

Now to show the student name with the course name which he had studied like,

**Result**
---------------------------
Student        Course
---------------------------
ahmed         physic
ahmed         maths
ahmed         computer
ahmed         chemistry
ali           physic
ali           maths
john          computer
john          chemistry
king          physic
king          maths

I build following query

select s.name as Student, c.name as Course from student s, course c join bridge b on c.id = b.cid order by s.name

But it does not return the required result...

And what would be for normalized form, if I want to find who is manager over other:

**employee**
-------------------
id        name
-------------------
1         ali
2         king
3         mak
4         sam
5         jon

**manage**
--------------
mid      eid
--------------
1         2
1         3
3         4
4         5

And wants to get this result:

**result**
--------------------
Manager      Staff
--------------------
ali          king
ali          mak
mak          sam
sam          jon
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
PHP Ferrari
  • 15,754
  • 27
  • 83
  • 149
  • in the first result you wrongly set data for ahmed and ali – NineCattoRules Jan 23 '17 at 09:13
  • We have 4 tables: name, address, email, phone SELECT A.personID, B.address, C.emailID, D.mobnumber FROM name AS A INNER JOIN address AS B ON A.personID = B.personID INNER JOIN email AS C ON A.personID = C.personID INNER JOIN phone AS D ON A.personID = D.personID This is assuming personID is present in all the tables. This query would display Person ID, Address, Email, Phone number where person ID is same in all the tables since it's an inner join. Hope this helps :) – JWC May Apr 10 '21 at 15:52

11 Answers11

250

Use ANSI syntax and it will be a lot more clear how you are joining the tables:

SELECT s.name as Student, c.name as Course 
FROM student s
    INNER JOIN bridge b ON s.id = b.sid
    INNER JOIN course c ON b.cid  = c.id 
ORDER BY s.name 
Machavity
  • 30,841
  • 27
  • 92
  • 100
D'Arcy Rittich
  • 167,292
  • 40
  • 290
  • 283
  • 10
    @Muhammad: Our answers are the same, they differ only in syntax. If you are not aware of `ANSI` syntax, it is well worth your time to learn it. It will help you avoid `JOIN` errors like you have made in the future. – D'Arcy Rittich Sep 14 '10 at 14:38
170

Simply use:

select s.name "Student", c.name "Course"
from student s, bridge b, course c
where b.sid = s.sid and b.cid = c.cid 
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
raisyn
  • 4,514
  • 9
  • 36
  • 55
  • 3
    See http://stackoverflow.com/questions/13476029/multiple-table-select-vs-join-performance – thdoan Aug 30 '14 at 11:51
  • 3
    Nice and simple, but FWIW consider the following blog re this syntax: https://sqlblog.org/2009/10/08/bad-habits-to-kick-using-old-style-joins as mentioned in https://stackoverflow.com/a/13476050/199364 – ToolmakerSteve Jan 21 '19 at 01:53
  • 9
    NO, NO, NO, NO, NO! Don't use this legacy, ancient, over 25 year old join syntax any more! Use Explicit joins like in [this answer!!](https://stackoverflow.com/a/3709583/575376) – juergen d Nov 10 '20 at 14:11
18

For normalize form

select e1.name as 'Manager', e2.name as 'Staff'
from employee e1 
left join manage m on m.mid = e1.id
left join employee e2 on m.eid = e2.id
PHP Ferrari
  • 15,754
  • 27
  • 83
  • 149
5
SELECT *
FROM user u
JOIN user_clockits uc ON u.user_id=uc.user_id
JOIN clockits cl ON cl.clockits_id=uc.clockits_id
WHERE user_id = 158
Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Ali Umair
  • 690
  • 7
  • 10
  • 2
    This answer looks very similar to answers already given 5 years earlier. What about your answer do you feel is important, and missing from existing answers? – ToolmakerSteve Jan 21 '19 at 02:02
2

Don't join like that. It's a really really bad practice!!! It will slow down the performance in fetching with massive data. For example, if there were 100 rows in each tables, database server have to fetch 100x100x100 = 1000000 times. It had to fetch for 1 million times. To overcome that problem, join the first two table that can fetch result in minimum possible matching(It's up to your database schema). Use that result in Subquery and then join it with the third table and fetch it. For the very first join --> 100x100= 10000 times and suppose we get 5 matching result. And then we join the third table with the result --> 5x100 = 500. Total fetch = 10000+500 = 10500 times only. And thus, the performance went up!!!

1

join query with three tables and we want two values from the same column we set the alias name for every table in the joins. Same table name also declare as a different names.

const sql = `select p.ID,p.purchaseamount,urs.name as 
            buyername,pd.productname,
            pd.amount,urs1.name as sellername
            from  purchases p
            left join products pd on p.productid=pd.ID
            left join users urs on p.userid=urs.ID 
            left join users urs1 on  pd.userid=urs1.ID`
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
Pavithra
  • 11
  • 3
0
SELECT 
employees.id, 
CONCAT(employees.f_name," ",employees.l_name) AS   'Full Name', genders.gender_name AS 'Sex', 
depts.dept_name AS 'Team Name', 
pay_grades.pay_grade_name AS 'Band', 
designations.designation_name AS 'Role' 
FROM employees 
LEFT JOIN genders ON employees.gender_id = genders.id 
LEFT JOIN depts ON employees.dept_id = depts.id 
LEFT JOIN pay_grades ON employees.pay_grade_id = pay_grades.id 
LEFT JOIN designations ON employees.designation_id = designations.id 
ORDER BY employees.id;

You can JOIN multiple TABLES like this example above.

Sebastian Brosch
  • 42,106
  • 15
  • 72
  • 87
sameerNAT
  • 95
  • 1
  • 3
  • 1
    There already are multiple answers, from years earlier, that show "joining multiple tables". What does your answer add to the discussion? – ToolmakerSteve Jan 21 '19 at 02:27
0

Just adding a point to previous answers that in MySQL we can either use

table_factor syntax 

OR

joined_table syntax

mysql documentation

Table_factor example

SELECT prd.name, b.name 
FROM products prd, buyers b

Joined Table example

SELECT prd.name, b.name 
FROM products prd
 left join buyers b on b.bid = prd.bid;

FYI: Please ignore the fact the the left join on the joined table example doesnot make much sense (in reality we would use some sort of join table to link buyer to the product table instead of saving buyerID in product table).

0
Query for three table join and limit set

SELECT * FROM (SELECT t1.follower_userid, t2.*, t3.login_thumb, t3.login_name, 
  t3.bio, t3.account_status, t3.gender
     FROM videos t2
      LEFT JOIN follower t1
        ON t1.follower_userid = t2.user_id 
         LEFT JOIN videos_user t3 
          ON t1.follower_userid  = t3.login_userid
           WHERE t1.following_userid='$userid'
            LIMIT $startpoint , $limit) AS ID 
             ORDER BY ID DESC
Chirag Patel
  • 559
  • 6
  • 14
-1

Use this:

SELECT s.name AS Student, c.name AS Course 
FROM student s 
  LEFT JOIN (bridge b CROSS JOIN course c) 
    ON (s.id = b.sid AND b.cid = c.id);
Derlin
  • 9,572
  • 2
  • 32
  • 53
  • 1
    This answer adds nothing new to this question and uses strange (if not plain wrong syntax, I'd be surprised if this was even valid in MySQL). – AeroX Feb 16 '15 at 16:22
  • I disagree with AeroX. Ansi join syntax is meant to disambiguate problems with the old school comma/where join syntax. I'm looking to see if MySql supports ansi join syntax specifically. – Larry Smith May 14 '15 at 21:30
-1

Query to join more than two tables:

SELECT ops.field_id, ops.option_id, ops.label
FROM engine4_user_fields_maps AS map 
JOIN engine4_user_fields_meta AS meta ON map.`child_id` = meta.field_id
JOIN engine4_user_fields_options AS ops ON map.child_id = ops.field_id 
WHERE map.option_id =39 AND meta.type LIKE 'outcomeresult' LIMIT 0 , 30
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Manish
  • 639
  • 6
  • 17
  • There already are multiple answers, from years earlier, that show "joining multiple tables". What does your answer add to the discussion? – ToolmakerSteve Jan 21 '19 at 02:28
  • @ToolmakerSteve there are lot newer than my answer can you delete them all ? In my answer it is simpler to use with multiple condition like number and string – Manish Mar 11 '22 at 12:47