2016-07-27 67 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