How you can use the SQL JOIN function correctly

Hi! In this tutorial I will explain to you how you can use the SQL JOIN function correctly. If you want to extract information from two or more table which have any identical column names.

I have created two tables in my database:

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 extract information from my tables, I have writed this query:

$join = mysql_query("SELECT * FROM `customers` LEFT JOIN `date` ON customers.id=date.customerid");

This query will display all information from my first table(customers) and the information from my date table.

$join = mysql_query("SELECT * FROM `customers` RIGHT JOIN `date` ON customers.id=date.customerid");

This query will display only the data from my first table where exists information in my second table with customerid.

Video tutorial:

In my next tutorial I will explain to you how you can  join three tables in SQL!









Leave a Comment