2016-07-27 85 views
0

假設我已經有了這個數據庫:避免重複過程中加入

table1: 
- id 
- name 

table2: 
-id 
-name 
-date 
-table1id 

如果我這樣做

SELECT table1.id, table1.name,table2.date 
FROM table1 
LEFT JOIN table2 ON table1.id = table2.table1id 

我將有2行。

我只想加入table2中最近一次的行。有沒有辦法通過MySQL來做到這一點,或者我必須在查詢之後用PHP之類的東西來做到這一點嗎?

在罰款我想要一行,table1.id,table1.name和來自table2鏈接條目的最近日期。

+0

是,使用WHERE table2.date – rad11

+0

WHERE table2.date =? – Vico

+0

我也想知道'where table2.date'什麼? –

回答

2

使用GROUP BY和聚集功能MAX

SELECT table1.id, table1.name, MAX(table2.date) AS `date` 
FROM table1 
LEFT JOIN table2 ON table1.id = table2.table1id 
GROUP BY table1.id