简体   繁体   中英

Syntax issue in MySQL left join

In mysql's manual ( https://dev.mysql.com/doc/refman/8.0/en/join.html ) there is an example:

SELECT t1.name, t2.salary
FROM employee AS t1 INNER JOIN info AS t2 ON t1.name = t2.name;

Now,it is my case.Let me create a table and some data...

CREATE TABLE `tb` (
  `id` int(11) NOT NULL AUTO_INCREMENT ,
  `name` text ,
  `year` int(2) ,
  `num` int(5) ,
  PRIMARY KEY (`id`)
);

INSERT INTO tb (id, name,year,num) VALUES 
('1', 'a','19', 500),
('2', 'a','18', 400),
('3', 'b','19', 400),
('4', 'b','18', 200),
('5', 'c','19', 400),
('6', 'c','18', 100);

Here is my test data.

+----+------+------+------+
| id | name | year | num  |
+----+------+------+------+
|  1 | a    |   19 |  500 |
|  2 | a    |   18 |  400 |
|  3 | b    |   19 |  400 |
|  4 | b    |   18 |  200 |
|  5 | c    |   19 |  400 |
|  6 | c    |   18 |  100 |
+----+------+------+------+

I want to get a left join,left is 19's data, right is 18's data,such as below:

+------+------+------+------+
| name | num  | name | num  |
+------+------+------+------+
| a    |  500 | a    |  400 |
| b    |  400 | b    |  200 |
| c    |  400 | c    |  100 |
+------+------+------+------+

One kind of right left join is as below:

SELECT * FROM
(
    SELECT `name`, `num`
    FROM `tb`
    WHERE `year` = 19
) AS a
LEFT JOIN
(
    SELECT `name`, `num`
    FROM `tb`
    WHERE `year` = 18
) AS b ON a.`name` = b.`name`;

I wonder why the below can't get right result?

SELECT `name`, `num`
FROM `tb`
WHERE `year` = 19
AS a
LEFT JOIN
(
    SELECT `name`, `num`
    FROM `tb`
    WHERE `year` = 18
) AS b ON a.`name` = b.`name`;

Your last query has a syntax error. The WHERE clause must go at the end and you need to remove ambiguity in column names inside SELECT clause:

SELECT a.`name`, a.`num`, b.`num`
FROM `tb` AS a
LEFT JOIN (
    SELECT `name`, `num`
    FROM `tb`
    WHERE `year` = 18
) AS b ON a.`name` = b.`name`
WHERE `year` = 19;

Having said that, you can also write the query like so:

SELECT l.name, l.year, l.num, r.year, r.num
FROM tb AS l
LEFT JOIN tb AS r ON l.name = r.name AND r.year = 18
WHERE l.year = 19

This is the correct syntax:

SELECT * FROM (
    SELECT `name`, `num`
    FROM `tb`
    WHERE `year` = 19
    ) as a
LEFT JOIN (
    SELECT `name`, `num`
    FROM `tb`
    WHERE `year` = 18
    ) as b ON a.`name` = b.`name`;

See the demo .
Results:

| name | num | name | num |
| ---- | --- | ---- | --- |
| a    | 500 | a    | 400 |
| b    | 400 | b    | 200 |
| c    | 400 | c    | 100 |

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM