MySQL: 如何对具有多个条件的连接查询(子查询)求和?

MySQL: How to sum on joined queries (subqueries) with multiple conditions?

我有两个表:

Table Y:表示货币在什么时间段内有效

+-----------+---------+------+
| starttime | endtime | name |
+-----------+---------+------+
| 1         | 2       | Mark |
| 3.4       | 3.6     | Fred |
| 2         | 2.2     | Fred |
+-----------+---------+------+

Table Z

+-----------+---------+------+-------+
| starttime | endtime | name | money |
+-----------+---------+------+-------+
| 1.5       | 1.7     | Mark | 0.1   |
| 1.4       | 3.5     | Fred | 0.2   |
| 0.9       | 1.0     | Fred | 0.3   |
| 1.2       | 2.5     | Fred | 0.5   |
+-----------+---------+------+-------+

我想要的:

+------+---------------+
| name | sum_validmoney|
+------+---------------+
| Mark | 0.1           |
| Fred | 0.7           | **=> this is 0.2+0.5 (because those rows overlapped in start/endtime segments)**
+------+---------------+

我希望根据 Table Y 中指示的时间段约束(有界)对 Table Z 中的行求和。 也就是说,要在 Table Z 中求和的行必须在 Table Y 中找到的时间段内 (在 Table Z 上还有其他过滤器用于其他查询;但我认为这与此处无关)

我对 MySQL 很陌生。我试过子查询,但认为我遗漏了一些关键的东西;我不确定这是否可以在没有一些复杂的循环结构的情况下完成,mysql 似乎没有很好的装备。

您似乎想要过滤 table z 范围重叠范围至少在 table y.

中的行

如果是这样,一种方法是:

select name, sum(money) sum_valid_money
from z
where exists (
    select 1
    from y 
    where y.name = x.name and y.starttime <= x.endtime and y.endtime >= x.starttime
)
group by name