为什么此查询总是返回空行?

时间:2012-07-06 12:56:30

标签: mysql sql

我对这个问题感到非常疯狂,并想知道是否有一个天才,对于谁来说这只是一个孩子的游戏......?

此查询应建议随机用户登录用户,而登录用户与建议用户之间的关系不得以下列方式之一阻止:

  • by continents
  • 按国家/地区
  • 按年龄范围
  • 按性别划分
  • by id(blocker< - > blockee)

表结构

用户

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中的userid 中的cities匹配

blocked_countries

id | user_id | country_id | ...

blocked_continents

id | user_id | continent_id | ...

BLOCKED_USER

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变量中存储了登录用户的所有必要变量...如果您在查询中发现可以更好地完成的任何其他内容,我也非常乐意为您提供帮助!

非常感谢你!

1 个答案:

答案 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
...