2017-01-20 37 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);