如何获取今天或未来7天(周)过生日的朋友?

How to get friends who have birthday today or in the next 7 days (week)?

在创建此主题之前,我研究了整个社区,但没有发现任何与我想做的事情相近的东西。我正在开发一个小型社交网络,这是一个仅用于学术目的的 PHP 项目。


我的数据库中有以下表格:

Table Name: users
Columns:
   id => INT (Primary Key - AutoIncrement)
   name => VARCHAR(200)
   birthdate => DATE
   login => VARCHAR(60)
   password => VARCHAR(60)

Table Name: friends
Columns:
   id => INT (Primary Key - AutoIncrement)
   idRequester => INT (Foreign Key - users>>id)
   requestDate => DATE
   idRequested => INT (Foreign Key - users>>id)
   confirmationDate => DATE
   situation => CHAR(1) (A=Accepted | P=Waiting | R=Rejected)


通过以下查询,我可以获得当天的所有生日(不考虑友谊)。

SELECT id, name, DATE_FORMAT(birthdate, '%d/%m/%Y') AS dtbirth,
TIMESTAMPDIFF(YEAR, birthdate, NOW()) AS age
FROM users WHERE birthdate LIKE '%-06-21';


这类似于葡萄牙语论坛的另一个主题中提出的问题,在这个 link: Here

我需要得到所有今天或未来 7 天生日的朋友给定当前日期,这是来自特定用户 X。我不知道如何 JOIN tables users and friends 因为我们有两列,如果 X 是请求用户,那么我需要加入被请求的用户,否则 X 被请求,然后我加入请求者.

即获取今天或未来7天过生日的所有'user ID 50'位好友


如果有人可以帮助我,因为我不确定如何执行解决此问题并提高性能的查询。我相信它会帮助很多人,因为怀疑是出于学术目的而经常发生的事情。谢谢。

试试这个:我假设你的 birthdate 列只持有 data 而不是时间,你必须使用 OR 条件来满足两个或两个条件之一为真。它将 return 当前日期和 7th days 出生日期记录

SELECT id, name, DATE_FORMAT(birthdate, '%d/%m/%Y') AS dtbirth,
TIMESTAMPDIFF(YEAR, birthdate, NOW()) AS age
FROM users 
WHERE (birthdate = CURDATE() OR  birthdate = DATE_ADD(CURDATE(), INTERVAL 7 DAY))

--Replace `WHERE` with below line to Return records from Current date to next 7 days
WHERE birthdate BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 7 DAY)
SELECT id, name, DATE_FORMAT(birthdate, '%d/%m/%Y') AS dtbirth,
TIMESTAMPDIFF(YEAR, birthdate, NOW()) AS age
FROM users 
WHERE birthdate between  CURDATE() and  DATE_ADD(CURDATE(), INTERVAL 7 DAY))

您好,根据我的理解,您需要所有在今天和下周之间过生日的朋友参加一个特定的 user_id,并且您也对如何拉所有朋友感到困惑,因为有时 X人是请求友谊的人,有时 X 是请求友谊的人。

我在下面写了查询,希望对您有所帮助。

select ur.*, TIMESTAMPDIFF(YEAR, birthdate, NOW()) AS age 
 from users ur 
 inner join
 (
    -- getting all the friends who are accepted and the user was requested
   (
      select f.idRequester as friends_id
      from users u
      inner join friends f
      on (u.id=f.idRequested)
      where u.id=103 and situation = 'A'
   )
   union
   (
     -- getting all the friends who are accepted and the user was requester

     select f.idRequested as friends_id
     from users u
     inner join friends f
     on (u.id=f.idRequester)
     where u.id=103 and situation = 'A'
    )
  ) temp
    on(ur.id=temp.friends_id)
    /*
       this part compares if the day of birth lies 
       between today or next 7 days. 
    */ 
     WHERE DATE(CONCAT_WS('-', YEAR(curdate()), MONTH(birthdate), 
           DAY(birthdate))) BETWEEN CURDATE() AND DATE_ADD(CURDATE(),INTERVAL 7 DAY);

注意:我对 user_id 进行了硬编码,要使其动态化,您可以使用带参数的存储过程并用它替换硬编码部分。