SQL Joins
SQL Left
、Right
、Inner
、outer
Join~
SQL Joins
Demo
Schema
CREATE TABLE IF NOT EXISTS `t1` (
`id` int(6) unsigned NOT NULL,
`title` varchar(200) NOT NULL,
PRIMARY KEY (`id`,`title`)
) DEFAULT CHARSET=utf8;
INSERT INTO `t1` (`id`, `title`) VALUES
('1', 'title1'),
('2', 'title2');
CREATE TABLE IF NOT EXISTS `t2` (
`id` int(6) unsigned NOT NULL,
`name` varchar(200) NOT NULL,
PRIMARY KEY (`id`,`name`)
) DEFAULT CHARSET=utf8;
INSERT INTO `t2` (`id`, `name`) VALUES
('1', 'name1'),
('3', 'name3');
Data
-- based on answer https://stackoverflow.com/a/7745635/808921
> select * from t1;
| id | title |
|----|--------|
| 1 | title1 |
| 2 | title2 |
> select * from t2;
| id | name |
|----|-------|
| 1 | name1 |
| 3 | name3 |
Base Join
> select * from t1 left join t2 on t1.id = t2.id;
| id | title | id | name |
|----|--------|--------|--------|
| 1 | title1 | 1 | name1 |
| 2 | title2 | (null) | (null) |
> select * from t1 right join t2 on t1.id = t2.id;
| id | title | id | name |
|--------|--------|----|-------|
| 1 | title1 | 1 | name1 |
| (null) | (null) | 3 | name3 |
> select * from t1 inner join t2 on t1.id = t2.id;
| id | title | id | name |
|----|--------|----|-------|
| 1 | title1 | 1 | name1 |
Comments
Leave a comment