2013-08-23 53 views
1

我一直在设置一个小网站供用户登录和发布消息。我正在建立一个存储联系人的表格(以便用户可以在板上查看和发送消息)。我几乎完成配置,但遇到了障碍。如何筛选mysql中select语句的结果

When a user registers for the first time, an entry is created in each of two tables; users and contacts. The users table stores username and password stuff, the contacts table stores a directory of people on the system and whether they've been added to other people's contact lists. The tables look like this; 

mysql> select userid, firstname, lastname, username from users; 
+--------+-----------+----------+----------+ 
| userid | firstname | lastname | username | 
+--------+-----------+----------+----------+ 
|  63 | Chris  | Smith | csmith | 
|  64 | Susan  | Smith | ssmith | 
|  65 | Roger  | Smith | rsmith | 
|  66 | Diane  | Smith | dsmith | 
+--------+-----------+----------+----------+ 
4 rows in set (0.00 sec) 

mysql> select * from contacts; 
+----------+---------+-----------+ 
| username | contact | confirmed | 
+----------+---------+-----------+ 
| csmith | csmith | 0   | 
| ssmith | ssmith | 0   | 
| rsmith | rsmith | 0   | 
| dsmith | dsmith | 0   | 
| csmith | dsmith | 2   | 
| dsmith | csmith | 2   | 
| dsmith | ssmith | 1   | 
| dsmith | rsmith | 1   | 
+----------+---------+-----------+ 
8 rows in set (0.00 sec) 

用户能够进行身份验证,他们能够添加和删除对方没有问题。 “已确认”列存储联系人的状态。 0用于指示注册时为用户创建的联系人中的初始条目。 1表示邀请是否从用户名发送到联系人但尚未确认。 2表示联系已被确认。通过在网站的不同部分进行选择查询,我可以显示用户的联系人列表,或只显示他们可能添加但尚未添加的系统上的人员列表。除了不请自来的联系人目录列表外,几乎一切正常。

联系人的初始列表应该由确认状态为0的用户的select查询输出组成,它应该省略用户自己的条目(因此,他们不应该自己添加自己)和(使我感到困扰的部分),它也应该忽略具有用他们自己的用户名确认1(发送邀请)或2(联系确认)的人。

所以,csmith应该在他的用户目录ssmith和rsmith中看到,但不应该看到dsmith,因为dsmith已经被添加到他的联系人(确认联系人第5条中的2)。

所以,我一直很难想出一种方法来查询给定这些规则的目录查询。我如何创建一个规则呢?

select contact from contacts where username!=$authenticated_user and confirmation='0'

这会给我的系统上的用户列表中,除了我自己,谁一直没有被邀请但人们。

但随后也从输出翻出

select contact from contacts where username=$authenticated_user and confirmation='1' and confirmation='2' 

使已经邀请和/或添加的用户列表中显示不出来了吗?

任何帮助表示赞赏。

回答

0
SELECT DISTINCT `contact` 
FROM test.test 
WHERE `contact` 
NOT IN 
    (SELECT `contact` 
    FROM test.test 
    WHERE `username` = "csmith"); 

相互友谊任何条目格式给出(一个 - > b)和(B - > A),所有的邀请都在格式给出(A - > B)简化了测试 - 我们只是必须查找任何没有$ username(p.ex.“csmith”)的用户作为联系人条目中的用户名。

(这也不会排除谁是通过连接至自己的默认(用户A,A,0)。)

+0

不,这不能解决问题,但我认为这是在正确的轨道上。我对这个语法有疑问。当我阅读它时,我的印象是它试图说,“如果表中没有包含子查询的输出,则从表中选择用户名”,对吗?我可以添加多个子查询吗? – Kimomaru

+0

你,但我会建议首先在该主题读书时,它可能会导致可怕的表现 - 我真的很感兴趣,究竟没有为你工作,从测试情况来看,并通过逻辑我想指望它满足您的要求,请您详细说明一下? – Xevelion

+0

是的,谢谢你的提问 - 我不想给你太多负担。以下是引擎盖下发生的事情。假设3个用户; csmith,dsmith和rsmith。它们都在用户表中有条目,当它们最初注册时,在用户名,用户名,0形式的联系人表中创建一个条目(如果用户名是csmith,它看起来像“csmith,csmith,0” )我需要在 – Kimomaru