2017-01-20 40 views
1

table_1与ID的独特的记录和数据加入多个列在表1与多个列在表2与附加条件的MySql

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); 

...但它失败了。

任何建议为新手?谢谢。

+2

欢迎堆栈溢出。你应该知道“但它失败”并不是一个描述性的描述性方式来描述你的问题。它给出了一个错误信息?如果是这样,错误是什么?它没有错误,但没有给出你期望的结果?如果是这样,你期望什么,它做了什么?另外,每个表的“SHOW CREATE TABLE”输出是什么?请帮助我们帮助你。 –

+0

'table2'的主键是什么?按照Bill的建议发布架构。 –

+0

由于实际表格非常重要,我决定发布一个基于简化的“虚拟”替代品的问题。就原始表而言,table1中只有一个主键(id),而table2中没有主键。我是一个领域的新手,所以很抱歉我的笨拙。 @Thorsten Kettner的回答证明是完美的。 –

回答

0

你就近了。但是,您选择的最大time_lapseid,然后您的行为就好像您只选择了一个记录,只有一个time_lapse。在你的子查询的选择列表中使用IN并有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); 

那么你是外加入表2,但希望WHERE子句中它一定的标准。这不起作用(因为外连接记录中的列为空)。

同样的查询一点点与真正的外漂亮加入:

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);