MySql - 只取多个可能的连接值中的最大值
MySql - Take only the max of multiple possible join values
抱歉,如果我想问的内容令人困惑,我过度简化了一个非常复杂的查询以解决问题。
假设我有包含以下列的 TableA:item_id;价格;日期。
我也有一个包含相同三列的 TableB,并且两个表中只有 ID 匹配。
示例:
Table A:
+---------+-------+------------+
| item_id | price | date |
+---------+-------+------------+
| 1 | 60 | 2020/08/04 |
+---------+-------+------------+
| 2 | 100 | 2020/07/23 |
+---------+-------+------------+
Table B:
+---------+-------+------------+
| item_id | price | date |
+---------+-------+------------+
| 1 | 80 | 2020/08/05 |
+---------+-------+------------+
| 2 | 70 | 2020/07/24 |
+---------+-------+------------+
| 2 | 90 | 2020/07/20 |
+---------+-------+------------+
| 2 | 60 | 2020/06/20 |
+---------+-------+------------+
我想使用 MySql 连接这两个表,但条件是 TableB 的日期必须最接近 TableA 的日期,但要早于。
Expected result:
+---------+---------+---------+
| item_id | price A | price B |
+---------+---------+---------+
| 1 | 60 | NULL | (As B date is superior to A)
+---------+---------+---------+
| 2 | 100 | 90 | (I ignore the superior(s), and of the other 2 I take max date)
+---------+---------+---------+
我尝试执行 LEFT JOIN,但它在输出中添加了多行,我不确定如何正确编写条件。我刚开始编写这样的复杂查询,我 2 天前唯一知道的是非常基础的,所以当我尝试 google 方法来做到这一点时,我结果更加困惑。
感谢阅读!
我认为这里最简单的方法是相关子查询,它从第二个 table 中恢复与 id
匹配且具有较早的 date
的行,然后带来价格“顶”行:
select
a.item_id,
a.price price_a
(
select b.price
from tableb b
where b.id = a.id and b.date < a.date
order by b.date desc
limit 1
) price_b
from tablea a
为了提高性能,请考虑 tableb(id, date, price)
上的索引。
抱歉,如果我想问的内容令人困惑,我过度简化了一个非常复杂的查询以解决问题。
假设我有包含以下列的 TableA:item_id;价格;日期。
我也有一个包含相同三列的 TableB,并且两个表中只有 ID 匹配。
示例:
Table A:
+---------+-------+------------+
| item_id | price | date |
+---------+-------+------------+
| 1 | 60 | 2020/08/04 |
+---------+-------+------------+
| 2 | 100 | 2020/07/23 |
+---------+-------+------------+
Table B:
+---------+-------+------------+
| item_id | price | date |
+---------+-------+------------+
| 1 | 80 | 2020/08/05 |
+---------+-------+------------+
| 2 | 70 | 2020/07/24 |
+---------+-------+------------+
| 2 | 90 | 2020/07/20 |
+---------+-------+------------+
| 2 | 60 | 2020/06/20 |
+---------+-------+------------+
我想使用 MySql 连接这两个表,但条件是 TableB 的日期必须最接近 TableA 的日期,但要早于。
Expected result:
+---------+---------+---------+
| item_id | price A | price B |
+---------+---------+---------+
| 1 | 60 | NULL | (As B date is superior to A)
+---------+---------+---------+
| 2 | 100 | 90 | (I ignore the superior(s), and of the other 2 I take max date)
+---------+---------+---------+
我尝试执行 LEFT JOIN,但它在输出中添加了多行,我不确定如何正确编写条件。我刚开始编写这样的复杂查询,我 2 天前唯一知道的是非常基础的,所以当我尝试 google 方法来做到这一点时,我结果更加困惑。
感谢阅读!
我认为这里最简单的方法是相关子查询,它从第二个 table 中恢复与 id
匹配且具有较早的 date
的行,然后带来价格“顶”行:
select
a.item_id,
a.price price_a
(
select b.price
from tableb b
where b.id = a.id and b.date < a.date
order by b.date desc
limit 1
) price_b
from tablea a
为了提高性能,请考虑 tableb(id, date, price)
上的索引。