0

我不确定这是如何正确调用的,所以我将尝试用一个例子来解释自己:

想象一下,在 2013 年 1 月 1 日,你开始上学X。我们将其输入到 MySQL 表中,例如:

user | day      | school
1    | 1.1.2013 | X

现在,在 2013 年 6 月 1 日,您将学校更改为Y. 让我们输入这个事实:

user | day      | school
1    | 1.1.2013 | X
1    | 1.6.2013 | Y

再一次,你第三次换学校:

user | day      | school
1    | 1.1.2013 | X
1    | 1.6.2013 | Y
1    | 4.3.2015 | Z

现在,查询

2013 年 3 月 1 日你在哪所学校上学?

答案是:X

我们如何将这样的查询写入 MySQL 以获得正确的答案?

注意:如果需要,MySQL 表结构可以与我提供的不同。
注2:不是家庭作业。这是我面临的真实情况,但我还没有创建我的表,因为我不确定到目前为止最好的解决方案是什么。

4

1 回答 1

0

In order to make it properly store the 'day' column in DATE format - yyyy-mm-dd so you can sort it. and then run this. It will give you all days (actually only the most recent one, because of the LIMIT 1) in the past of the selected date, when the user signed in a school starting from the most recent one.

SELECT * FROM {table_name} WHERE day <= '2013-03-01' ORDER BY day DESC LIMIT 1

In your case you will get school 1 since 2013-01-01

Edit:

in case your expediture table contains the date (in DATE format) you can use a subquery.

SELECT e.*, (SELECT school FROM {table_name} WHERE day <= e.date ORDER BY day DESC LIMIT 1) AS school_attended
FROM expenditures e;

If you provide the expeditures table scheme I can provide a better way probably.

于 2013-03-25T15:02:16.060 回答