仅从另一个表加入最新记录: - 删除复制

时间:2014-11-19 12:04:38

标签: mysql join

我有2个表让我们说table1和table2 table 1master数据而table 2child。我必须找出两个表中与给定table1.id对应的记录。但table2对应table1.id的记录超过1条。所以我想先从table2对应的table1.id过滤最新记录,然后对来自table2和table1的过滤数据应用连接。

table1= location_grids
table2= local_ads

跟着我在做什么?

SELECT  * FROM `location_grids`as l
LEFT JOIN `local_ads` la ON `la`.`location_grid_id` = `l`.`id`
Inner join (SELECT id, location_grid_id, max(booked_till) as maxbooked 
            from local_ads group by location_grid_id ) as b 
            on la. location_grid_id = b.location_grid_id 
            and la.booked_till = b.maxbooked
WHERE `l`.`location_id` =  '1'
AND `l`.`flag` =  1

查询返回未经过滤的数据。如何过滤然后应用数据连接。任何帮助将不胜感激。

table1: - 位置网格 enter image description here table2: - local_ad enter image description here

1 个答案:

答案 0 :(得分:0)

终于得到了解决方案: - 我正在寻找以下查询。

SELECT location_grid_id, user_id, booked_from, booked_till, purpose, category, duration, price, MAX( created ) 
FROM local_ads
GROUP BY location_grid_id

这里我想用特定id的最新记录运行join,因为local_ads中必须存在许多记录