How to JOIN three or more tables with SQL query

Hi guys! In my last tutorial I have spoken about how you can join two tables by using the SQL JOIN function. In this tutorial I will explain to you how you can join three or more tables by using the SQL JOIN function.

I have three tables in my database:

CREATE TABLE IF NOT EXISTS `about` (
`id` int(3) NOT NULL,
`customerid` bigint(3) NOT NULL,
`age` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;

INSERT INTO `about` (`id`, `customerid`, `age`) VALUES
(1, 1, '1985-08-01'),
(2, 2, '1990-09-17'),
(3, 3, '1998-05-27');

CREATE TABLE IF NOT EXISTS `customers` (
`id` int(3) NOT NULL,
`name` varchar(20) NOT NULL,
`city` varchar(20) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;

INSERT INTO `customers` (`id`, `name`, `city`) VALUES
(1, 'john', 'new york'),
(2, 'carlo', 'rome'),
(3, 'jean', 'paris');

CREATE TABLE IF NOT EXISTS `date` (
`id` int(3) NOT NULL,
`customerid` bigint(3) NOT NULL,
`date` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;

INSERT INTO `date` (`id`, `customerid`, `date`) VALUES
(1, 2, '2015-01-17'),
(2, 3, '2015-01-17'),
(3, 2, '2015-01-18');

To join three or more tables you must only add another JOIN function:

$join = mysql_query("SELECT * FROM `customers` LEFT JOIN `date` ON customers.id=date.customerid"); // here I have joined two tables

$join = mysql_query("SELECT * FROM `customers` JOIN `date` ON customers.id=date.customerid LEFT JOIN about ON customers.id=about.customerid"); // here I have joined three tables and this query will display the data by `about` table.

Video tutorial:









Leave a Comment