Tuesday, March 12, 2013

LEFT JOIN in database

How to join at least two tables from database?

First create tables:

1. Table with cars:
CREATE TABLE `cars` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `make` varchar(50) DEFAULT NULL,
  `model` varchar(50) DEFAULT NULL,
  `year` date DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

2. Table with users:
CREATE TABLE `users` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `cars_id` int(10) DEFAULT NULL,
  `name` varchar(40) DEFAULT NULL,
  `surname` varchar(40) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Now insert some rows with data to our tables.

There is foreign key - cars_id - in table users.
We will use foreign key to join cars with users.

INSERT INTO
        cars
        (
            make,
            model,
            year
        )
    VALUES
        (
            "Opel",
            "Vectra",
            "2012-05-25"
        );

INSERT INTO
        users
        (
            cars_id,
            name,
            surname
        )
    VALUES
        (
            1,
            "John",
            "Smith"
        );
And now you can join our tables:
SELECT
  *
FROM
  cars
LEFT JOIN users ON users.cars_id = cars.id

No comments: