如何查询与婚姻/死亡日期相关的信息

时间:2014-01-11 08:21:44

标签: mysql

    create users (id, gender, name, birth_date, married_on, died_on, ..)
    create user_relationships (id, user_id1, user_id2, relationship_type)

users (1, "M", "John", ..)
users (2, "F", "Mary", ..)
user_relationships (1, 1, 2, "married-to")

我该如何查询以下内容?

a. Users who are celebrating their birthdays next week.
b. Users whose marriage dates falling on the next week (Output should include Mr & Mrs John)
c. Users who died, the same time next week.

1 个答案:

答案 0 :(得分:2)

  1.   

    下周庆祝生日的用户。

    一种方法是看他们一个星期的年龄是否大于他们今天的年龄:

    SELECT *
    FROM   users
    WHERE  TIMESTAMPDIFF(YEAR, birth_date, CURRENT_DATE + INTERVAL 1 WEEK) >
           TIMESTAMPDIFF(YEAR, birth_date, CURRENT_DATE)
    
  2.   

    结婚日期在下周的用户。

    类似地:

    SELECT *
    FROM   users
    WHERE  TIMESTAMPDIFF(YEAR, married_on, CURRENT_DATE + INTERVAL 1 WEEK) >
           TIMESTAMPDIFF(YEAR, married_on, CURRENT_DATE)
    
  3.   

    死亡的用户,下周同一时间。

    我会留下这个作为读者的练习。