请帮忙,我是mySQL新手。 我想知道如何编写查询以生成以下结果:
table1
+-----+------+-------+
| id1 | id2 | col1 |
+-----+------+-------+
| 9 | 1 | foo 1 |
+-----+------+-------+
| 9 | 2 | foo 2 |
+-----+------+-------+
| 9 | 3 | foo 3 |
+-----+------+-------+
| 8 | 4 | foo 4 |
+-----+------+-------+
| 7 | 5 | foo 5 |
+-----+------+-------+
table2
+-----+------+-------+
| id2 | col2 | col3 |
+-----+------+-------+
| 1 | 2018 | bar 1 |
+-----+------+-------+
| 3 | 2018 | bar 2 |
+-----+------+-------+
| 1 | 2017 | bar 3 |
+-----+------+-------+
| 2 | 2017 | bar 4 |
+-----+------+-------+
想要得到id1 = 9
和2018
相关的表1和表2结果。
+-----+-------+-------+------+--------+
| id1 | id2 | col1 | col2 | col3 |
+-----+-------+-------+------+--------+
| 9 | 1 | foo 1 | 2018 | bar 1 |
+-----+-------+-------+------+--------+
| 9 | 2 | foo 2 | 2018 | "NULL" |
+-----+-------+-------+------+--------+
| 9 | 3 | foo 3 | 2018 | bar 2 |
+-----+-------+-------+------+--------+
到目前为止,我已经尝试了以下方法,但是还没有按照我期望的格式返回数据:
SELECT
*
FROM
table1 a
LEFT JOIN
table2 b ON a.id2 = b.id2
WHERE
a.id1 = 9 AND b.col2 = 2018
感谢并非常感激。 涉及 IT 技术的相关内容。