使用附加条件 MySql 将 table1 中的多列与 table2 中的多列连接起来
Joining multiple columns in table1 with multiple columns in table2 with additional condition MySql
我 table_1
具有唯一的 ID 记录和多列数据
和
table_2
多行涉及特定 ID 和多列。例如,table2
中的一列是 time_lapse。
我需要将这两个表与保存的所有列连接起来,但只有 table2
中具有最高 time_lapse 值的那些行。
我正在尝试这种方式...
create table as new_table
select table1.*, table2.* from
table1 left join table2
on table1.id=table2.id
where time_lapse=
(select max(time_lapse) from table2
group by id);
...但是失败了。
对新手有什么建议吗?谢谢。
你很接近。但是您 select 每个 id
的最大值 time_lapse
然后您的行为就好像您只 select 编辑了一条记录只有一条 time_lapse
。使用 IN
并在子查询的 select 列表中包含 id
:
create table as new_table
select table1.*, table2.* from
table1 left join table2
on table1.id=table2.id
where (table2.id, table2.time_lapse) in
(select id, max(time_lapse) from table2
group by id);
那么你是 outer-joining 表 2,但希望在 WHERE
子句中对它有特定的条件。这不起作用(因为 outer-joined 记录中的列为空)。
相同的查询使用真正的外连接更漂亮:
create table as new_table
select t1.*, t2.*
from table1 t1
left join table2 t2 on t1.id = t2.id
and (t2.id, t2.time_lapse) in
(select id, max(time_lapse) from table2 group by id);
我 table_1
具有唯一的 ID 记录和多列数据
和
table_2
多行涉及特定 ID 和多列。例如,table2
中的一列是 time_lapse。
我需要将这两个表与保存的所有列连接起来,但只有 table2
中具有最高 time_lapse 值的那些行。
我正在尝试这种方式...
create table as new_table
select table1.*, table2.* from
table1 left join table2
on table1.id=table2.id
where time_lapse=
(select max(time_lapse) from table2
group by id);
...但是失败了。
对新手有什么建议吗?谢谢。
你很接近。但是您 select 每个 id
的最大值 time_lapse
然后您的行为就好像您只 select 编辑了一条记录只有一条 time_lapse
。使用 IN
并在子查询的 select 列表中包含 id
:
create table as new_table
select table1.*, table2.* from
table1 left join table2
on table1.id=table2.id
where (table2.id, table2.time_lapse) in
(select id, max(time_lapse) from table2
group by id);
那么你是 outer-joining 表 2,但希望在 WHERE
子句中对它有特定的条件。这不起作用(因为 outer-joined 记录中的列为空)。
相同的查询使用真正的外连接更漂亮:
create table as new_table
select t1.*, t2.*
from table1 t1
left join table2 t2 on t1.id = t2.id
and (t2.id, t2.time_lapse) in
(select id, max(time_lapse) from table2 group by id);