我有2个表让我们说table1和table2 table 1
是master
数据而table 2
是child
。我必须找出两个表中与给定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: - 位置网格 table2: - local_ad
答案 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中必须存在许多记录