我对这个问题感到非常疯狂,并想知道是否有一个天才,对于谁来说这只是一个孩子的游戏......?
此查询应建议随机用户登录用户,而登录用户与建议用户之间的关系不得以下列方式之一阻止:
id | username | country_id_home | timestamp_lastonline | gender | birthdate | allow_gender | age_min | age_max | ...
评论:birthdate
采用mysql-date格式(YYYY-MM-DD
),gender
(0 =女性,1 =男性),allow_gender
(0 =两者,1 =女性,2 =男性)
country_id | name | continent_id | ...
id | city_real | ...
评论:表loc_id_home
中的user
与id
中的cities
匹配
id | user_id | country_id | ...
id | user_id | continent_id | ...
id | user1_id | user2_id | ...
评论:user1为“blocker”,user2为“blockee”
我现在的查询是:
SELECT u.id AS user_id, u.username, u.fname, u.country_id_home, u.timestamp_reg, u.timestamp_upd, u.timestamp_lastonline, u.online_status, u.gender, u.birthdate, u.prof_pic,
(SELECT name FROM countries co WHERE co.country_id=u.country_id_home) AS country_name,
(SELECT city_real FROM cities ci WHERE ci.id=u.loc_id_home) AS city ,
(SELECT region_name FROM regions r WHERE r.id=u.region_id_home) AS region,
(SELECT region_short FROM regions r WHERE r.id=u.region_id_home) AS region_short
FROM user_d1 u
LEFT JOIN (
SELECT DISTINCT user2_id AS blockee_id
FROM blocked_user
WHERE user1_id = :user1_id1
)this_user_blocked ON u.id = this_user_blocked.blockee_id
LEFT JOIN (
SELECT DISTINCT user1_id AS blocker_id
FROM blocked_user
WHERE user2_id = :user1_id2
)blocked_this_user ON u.id = blocked_this_user.blocker_id
WHERE
(allow_gender=0 OR allow_gender=:user1_allow_gender)
AND age_min<=:user1_age1
AND age_max>=:user1_age2
AND prof_status<>2
AND this_user_blocked.blockee_id IS NULL AND blocked_this_user.blocker_id IS NULL
AND NOT EXISTS (SELECT 1 FROM blocked_countries bc WHERE bc.user_id=u.id AND bc.country_id =:user1_country)
AND NOT EXISTS (SELECT 1 FROM blocked_countries bc WHERE bc.user_id=:user1_id3 AND bc.country_id = u.country_id_home)
AND EXISTS (
SELECT 1 FROM user_d1 u2
WHERE u2.id=:user1_id4
AND (u2.allow_gender=0 OR u2.allow_gender=(u.gender+1))
AND age_min<=(DATEDIFF(NOW(),u.birthdate))
AND age_max>=(DATEDIFF(NOW(),u.birthdate))
AND prof_status<>2
)
LIMIT 0,6
如果没有最后一个AND EXISTS...
,结果集不为空,但是像这样它总是不会返回任何结果。然而,未被大陆阻挡,尚未按timestamp_lastonline
...
上一次AND EXISTS...
我做错了什么?应该用JOIN
来完成吗?我也尝试过,但它也给出了一个空洞的结果......
我已经在SESSION变量中存储了登录用户的所有必要变量...如果您在查询中发现可以更好地完成的任何其他内容,我也非常乐意为您提供帮助!
非常感谢你!
答案 0 :(得分:6)
我认为这是因为DATEDIFF
,它返回两个日期之间的天数而不是年数。因此DATEDIFF
可能总是大于age_max。
编辑:你可以做这样的事情:
...
AND DATE_SUB(NOW(), INTERVAL age_max YEAR) <= u.birthdate
AND DATE_SUB(NOW(), INTERVAL age_min YEAR) >= u.birthdate
...