离开加入mysql问题

时间:2014-03-18 08:47:02

标签: php mysql join

这是我的疑问:

SELECT *
  FROM (
SELECT users.id, users.name, users.gender
       users.gender_preference, users.about_me
  FROM `users`
LEFT JOIN users_purchase ON users.id = users_purchase.user_id
     WHERE users.id != 20
       AND users.status = 1
       AND users.birthdate <= '1996-03-18' AND users.birthdate >= '1934-03-18'   AND users.gender = '2'                                    
  GROUP BY users.id
      ) AS myTable

我有另一个包含此字段的表:

id (primary),theBlocker, whoToBlock

我需要从我的查询结果中删除阻止者(&#39; theBlocker&#39;)阻止的用户(&#39; whoToBlock&#39;)。 有什么想法吗?

2 个答案:

答案 0 :(得分:1)

 SELECT *
  FROM (
  SELECT users.id, users.name, users.gender
         users.gender_preference, users.about_me
  FROM  `users`
  LEFT JOIN users_purchase ON users.id = users_purchase.user_id
  LEFT JOIN OTHERTABLE ON whoToBlock = users.id
  WHERE users.id != 20
  AND users.status = 1
  AND users.birthdate <= '1996-03-18' 
  AND users.birthdate >= '1934-03-18'   
  AND users.gender = '2' 
  AND OTHERTABLE.theBlocker IS NULL
  GROUP BY users.id
 ) AS myTable

我假设whoToBlock映射到你的user.id而theBlocker是一个布尔值。相应地编辑这些条件

答案 1 :(得分:1)

我对谁阻挡谁不清楚。对于您的示例,我假设您要排除用户20阻止的所有用户。将此添加到查询的简单方法是where子句:

SELECT u.id, u.name, u.gender, u.gender_preference, u.about_me
FROM `users` u LEFT JOIN
     users_purchase up 
     ON u.id = up.user_id
WHERE u.id <> 20 AND
      u.status = 1 AND
      u.birthdate <= '1996-03-18' AND
      u.birthdate >= '1934-03-18' AND
      u.gender = '2' and
      NOT EXISTS (select 1
                  from blockers b
                  where b.theBlocker = 20 and b.whomToBlock = u.id
                 )                                
GROUP BY users.id;

请注意,我还删除了额外的子查询层并添加了表别名,以使查询更具可读性。