![](/img/trans.png)
[英]How would I get the birthdays of friends who are celebrating their birthday this week, this month and next month using MYSQL and PHP?
[英]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';
我需要从给定的用户X中获取今天或在给定的当前日期后7天生日的所有朋友。我不知道如何联接 用户和朋友表,因为我们有两列,如果X为请求用户,那么我需要加入被请求的用户,否则需要X,然后再加入请求者。
也就是说,获取今天或未来7天生日的所有“用户ID 50”朋友。
嗨,根据我的理解,您需要所有在今天和下周之间过生日的朋友使用一个特定的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进行了硬编码,为了使其动态化,您可能可以使用带参数的存储过程,并用它替换硬编码部分。
尝试一下:我假设您的birthdate
列仅保存data
没有时间,并且您必须使用OR
条件满足两个或两个条件之一。 它将返回当前日期和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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.