首页 > 解决方案 > SQL - 将 2 个表与日期进行比较

问题描述

我有 3 张桌子,分别是:

st with an id, startDate, endDate, customer_id and serivcedeal_Id.

servicedeal with id and name.

price with id, price, startDate and servicedeal_Id.

我在表中有以下数据:

wpwh_veosoft_crm_st

表 st

wpwh_veosoft_crm_servicedeal

餐桌服务优惠

wpwh_veosoft_crm_price

表价

如果我有以下数据:

桌子街

startDate = 2018-11-01
endDate = 2019-03-05
customer_Id = 355
Servicedeal_Id = 3

餐桌服务优惠

id = 3 
name = lille pakke

我只想从表价格中查看 id 为 13 的行,因为它是我的 startDate 2018-11-01 之前的壁橱日期

有没有人有可以解决问题的SQL?

提前致谢

标签: mysqlsql

解决方案


您可以使用相关子查询获取价格 ID:

select st.*,
       (select p.id
        from price p
        where p.Servicedeal_Id = st.Servicedeal_Id and
              p.startDate <= st.startDate
        order by p.startDate desc
        limit 1
       ) as price_id
from st;

如果您需要其他信息,可以join将其用作子查询或 CTE。如果您只想要价格,则只需选择该列而不是 id。

这种类型的查询可能是资源密集型的。您可能需要在price(Servicedeal_Id, startDate, id).


推荐阅读