【问题标题】:Mysql Join with max date and first rowMysql加入最大日期和第一行
【发布时间】: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. 属性表中的所有行
  2. 只有 1 行表单属性历史记录,其中任何日期列的最新日期为最新日期 例如。 (date1, date2, date3, date4) 之间的最新日期作为 latest_date 作为一列
  3. 如果 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


【解决方案1】:

请试试这个查询

Select proerties.id,proerties.property_address,proerties.owner from proerties 
left join ( Select Case when date(date1)>=date(date2) and date(date1)>=date(date3) and date(date1)>=date(date4) then date1 when date(date2)>=date(date1) and date(date2)>=date(date3) and date(date2)>=date(date4) then date2  when date(date3)>=date(date1) and date(date3)>=date(date2) and date(date3)>=date(date4) then date3  when date(date4)>=date(date1) and date(date4)>=date(date2) and date(date4)>=date(date3) then date3 END AS max_date,property_id  from property_history) as update_history on update_history.property_id=proerties.id

如果你得到预期的结果,请告诉我。

【讨论】:

  • 我没有检查你的解决方案,我做了我的查询
【解决方案2】:
SELECT properties.id, properties.parcel_id, properties.state, properties.county, properties.assessed_value, properties.in_same_zip, properties.in_same_state
FROM  properties left join (SELECT GREATEST(tax_history.date_paid_2nd_half_2,
     COALESCE(tax_history.date_paid_2nd_half_1, 0),
     COALESCE(tax_history.date_paid_1st_half_2, 0),
     COALESCE(tax_history.date_paid_1st_half_1, 0)) as latest_date, property_id from tax_history) as tax_history ON tax_history.property_id = properties.id
This query is working but it is very slow, I have thousands of records

【讨论】:

    猜你喜欢
    • 2015-05-16
    • 2012-05-01
    • 1970-01-01
    • 2016-08-10
    • 2021-04-07
    • 2010-10-26
    • 1970-01-01
    • 1970-01-01
    • 2021-12-15
    相关资源
    最近更新 更多