有条件的mysql加入?

时间:2012-05-02 16:11:30

标签: mysql

我有两个表,一个表用于用户,另一个表是user_interested_in_who表。

这个想法是,如果用户对另一个用户感兴趣,我会将这两个用户的ID插入user_interested_in_who表

我的表的架构是:

Users               user_interested_in_who
  id                id
  name              this_user (id from the users table)
                    interested_in_this_user (id from the users table)
                    interested_or_not (1 = yes, 0 = no)

所以我想通过将它们连接在一起来查询我的表,我的查询是这样的:

SELECT users.id, users.name, user_interested_in_who.interested_or_not
FROM users
LEFT JOIN user_interested_in_who
ON user_interested_in_who.this_user = 1 *//1 is the id of the current log in user*
GROUP BY users.id

这个查询的问题是interest_or_not列都有1.即使interest_or_not列在记录中有0

我的问题是,如果在user_interested_in_who表上找不到记录,如何查询它返回NULL?如果记录为0,如何查询它在user_interested_or_not列中返回0


编辑:

如何让它返回这种表:

table:
id | name | interested_or_not
1    jess   NULL
2    erika  1
3    jil    0
4    adrian NULL
....
1050 mich   1

2 个答案:

答案 0 :(得分:2)

您需要使用LEFT OUTER JOIN但在ON子句中没有文字值。

这将返回第一个表中的所有条目以及它们在第二个表中的匹配或NULL。

SELECT users.id, users.name, user_interested_in_who.interested_or_not
FROM users 
LEFT OUTER JOIN user_interested_in_who 
   ON user_interested_in_who.this_user = users.id 

不需要GROUP,并且您的示例案例(您已显示所有值?)不需要WHERE。如果您确实要限制用户ID,请按如下所示进行修改:

SELECT users.id, users.name, user_interested_in_who.interested_or_not
FROM users 
LEFT OUTER JOIN user_interested_in_who 
   ON user_interested_in_who.this_user = users.id 
WHERE users.id = 1

答案 1 :(得分:1)

您需要JOIN而不是LEFT JOINJOIN将只返回两个表中的记录您还需要一个where子句,而不是使用用户的登录ID来创建连接。

你不需要分组任何东西,这就是你总是得到1的原因。

这应该做你想要的。

SELECT users.id, users.name, user_interested_in_who.interested_or_not
FROM users
JOIN user_interested_in_who
ON user_interested_in_who.this_user = users.id
WHERE users.id=1;
相关问题