MYSQL仅在最大行上加入来自多个表的数据

时间:2017-12-13 19:18:01

标签: mysql join max

我有一个选择属性的查询,我需要加入它们以获取每个属性的最新活动,其中activity_status = 3(已完成交易)。当我得到它时,我需要让关闭交易的银行(banks.is_reward = 1

问题是数据分布在很多表中,所以当我加入获取所有结果,然后尝试限制为max(activity_date)时,我需要对结果进行分组,然后我不会从其他列中获取正确的数据。

Here is a SQL Fiddle

我能做到

Select * from properties
join
(SELECT deal_properties.property_id, activity.deal_id, activity.activity_date, banks.bank_id
FROM deal_properties
JOIN activity on activity.deal_id = deal_properties.deal_id
AND activity.activity_status = 3
JOIN banks ON banks.deal_id = activity.deal_id
AND banks.is_rewarded = 1) a
on a.property_id = properties.property_id;

这将获得所有已关闭的属性,奖励银行,但我似乎无法通过max(activity_date)来限制。

2 个答案:

答案 0 :(得分:1)

选项1

以下按照您当前的想法给出了您正在寻找的内容:

SELECT LastActivities.property_id, ActivityDetails.bank_id, LastActivities.activity_date 
FROM (
      SELECT p.property_id, MAX(a.activity_date) AS activity_date
      FROM properties p
      JOIN deal_properties dp
          ON dp.property_id = p.property_id
      JOIN activity a
          ON a.deal_id = dp.deal_id AND a.activity_status = 3
      GROUP BY p.property_id
) LastActivities

JOIN(
      SELECT a.activity_date, dp.property_id, b.bank_id 
      FROM deal_properties dp
      JOIN activity a
          ON a.deal_id = dp.deal_id AND a.activity_status = 3
      JOIN banks b
          ON b.deal_id = a.deal_id AND b.is_rewarded = 1
) ActivityDetails
  ON ActivityDetails.property_id = LastActivities.property_id 
  AND ActivityDetails.activity_date = LastActivities.activity_date

这是小提琴:HERE

选项2

下面是获得相同结果的另一种方法......这应该更高效,因为它只有一个派生表而不是两个。

SELECT p.property_id, b.bank_id, a.activity_date
FROM activity a
JOIN banks b
  ON b.deal_id = a.deal_id AND b.is_rewarded = 1
JOIN deal_properties dp
  ON dp.deal_id = a.deal_id
JOIN properties p
  ON p.property_id = dp.property_id
JOIN(SELECT p.property_id, max(a.activity_date) AS activity_date
    FROM activity a
    JOIN deal_properties dp
      ON dp.deal_id = a.deal_id
    JOIN properties p
      ON p.property_id = dp.property_id
     GROUP BY p.property_id
) latest
  ON latest.activity_date = a.activity_date AND latest.property_id = p.property_id

WHERE a.activity_status = 3

以下是选项2的小提琴:HERE

答案 1 :(得分:0)

看你的样品似乎需要

Select * from properties p
inner join 
( SELECT deal_properties.property_id as property_id , max(activity.activity_date) max_date
  FROM deal_properties
  INNER JOIN activity on activity.deal_id = deal_properties.deal_id 
                   AND activity.activity_status = 3
  INNER JOIN banks ON banks.deal_id = activity.deal_id AND banks.is_rewarded = 1
  group by property_id
  ) a on  a.property_id = p.property_id;