也许如何选择

时间:2018-07-21 14:39:28

标签: mysql sql

请帮助,我是mySQL的新手。我想知道如何编写查询以产生以下结果:

表1

+-----+------+-------+
| 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 = 92018的table1,table2

+-----+-------+-------+------+--------+
| 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

非常感谢。

2 个答案:

答案 0 :(得分:4)

你很近。将年份过滤器移至加入条件:

__dirname + '/../views/partials'

结果:

create table table1 (id1 int, id2 int, col1 varchar(20));
insert into table1 (id1, id2, col1) values (9, 1, 'foo 1');
insert into table1 (id1, id2, col1) values (9, 2, 'foo 2');
insert into table1 (id1, id2, col1) values (9, 3, 'foo 3');
insert into table1 (id1, id2, col1) values (8, 4, 'foo 4');
insert into table1 (id1, id2, col1) values (7, 5, 'foo 5');

create table table2 (id2 int, col2 int, col3 varchar(20));
insert into table2 (id2, col2, col3) values (1, 2018, 'bar 1');
insert into table2 (id2, col2, col3) values (3, 2018, 'bar 2');
insert into table2 (id2, col2, col3) values (1, 2017, 'bar 3');
insert into table2 (id2, col2, col3) values (2, 2017, 'bar 4');

SELECT 
    a.id1, a.id2, a.col1, 2018 as col2, b.col3
FROM
    table1 a
    LEFT JOIN table2 b ON a.id2 = b.id2 and b.col2 = 2018
WHERE
    a.id1 = 9

答案 1 :(得分:3)

您的问题中的重点似乎是

LEFT OUTER JOINt1.id2 = t2.id2 and t2.col2 = 2018结合使用 并为以下列中的年份列的不匹配值分配当前年份

select t1.id1, t1.id2, t1.col1, 
       coalesce(t2.col2,year(now())) as col2, 
       t2.col3
  from table1 t1
  left outer join table2 t2 
  on ( t1.id2 = t2.id2 and t2.col2 = 2018 )
 where t1.id1 = 9 
 order by t1.id2;

 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

SQL Fiddle Demo