在创建此主题之前,我对整个社区进行了研究,但是没有发现任何与我尝试做的事情接近的事情。我正在开发一个小型社交网络,这是一个仅用于学术目的的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”朋友。
答案 0 :(得分:2)
根据我的理解,您需要所有在今天和下周之间过生日的朋友使用一个特定的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进行了硬编码,为使其动态化,您可能可以使用带参数的存储过程,并用其替换硬编码部分。
答案 1 :(得分:0)
尝试:我假设您的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)
答案 2 :(得分:0)
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))