【发布时间】:2020-05-28 17:04:32
【问题描述】:
我有 2 个表属性和 property_history 构造类似的东西
proerties -
id | property_address | owner
1 | abc | xyz
2 | 123 | efg
property_history-
id | property_id | date1 | date2 | date3 | date4
1 | 1 | 2012-05-01 | 0000-00-00 | 2002-06-11 | 2006-06-11 |
2 | 1 | 2019-05-01 | 0000-00-00 | 2003-06-11 | 2007-06-11 |
3 | 1 | 0000-00-00 | 2011-06-11 | 2004-06-11 | 2011-06-11 |
4 | 1 | 0000-00-00 | 2020-01-31 | 2005-06-11 | 0000-00-11 |
我需要将这两个表加入为
- 属性表中的所有行
- 只有 1 行表单属性历史记录,其中任何日期列的最新日期为最新日期 例如。 (date1, date2, date3, date4) 之间的最新日期作为 latest_date 作为一列
- 如果 property_history 没有任何与属性 id 相关的行,那么 latest_date 应该为 null
【问题讨论】:
-
将 LEFT JOIN 与获取每个属性 ID 的最新行的子查询一起使用。请参阅stackoverflow.com/questions/7745609/… 了解如何编写该子查询。
-
StackOverflow 不是免费的编码服务。你应该try to solve the problem first。请更新您的问题以在minimal reproducible example 中显示您已经尝试过的内容。如需更多信息,请参阅How to Ask,并拨打tour :)
-
一个提示除了学习左连接之外,您可能还想为您的日期使用“GREATEST”函数... Greatest( ph.date1, ph.date2, ph.date3, ph .date4 )作为 MostRecentDate 的“ph”只是“property_history”表的一个简短别名
标签: mysql