2011-02-17 163 views
1

我很难生成好的SQL。 它是应用程序的关系部分。 我有3个表:用户( '身份证'),关系( 'USER_ID', 'member_id'),relationship_block( 'USER_ID', 'blocked_member_id')Sql加入3个表

我想获得所有成员属于用户与USER_ID没有被阻止。

位于'关系'表中但不在'relationship_blocked'表中的第一个'用户'表的记录。 前2我可以做JOIN,但是我想删除那些被阻止的。

Thanx。

编辑:找到了一个良好的信息大约在这里:http://explainextended.com/2010/05/27/left-join-is-null-vs-not-in-vs-not-exists-nullable-columns/

回答

2
select * 
    from users u 
     inner join relationship r 
      on u.user_id = r.user_id 
     left join relationship_block rb 
      on r.user_id = rb.user_id 
       and r.member_id = rb.blocked_member_id 
    where rb.user_id is null 
3
/* this would get the user */ 
SELECT * 
FROM users 
WHERE id = $ID 

/* build on this to get relationships */ 
SELECT * 
FROM users u 
JOIN relationship r ON r.user_id = u.id 
WHERE u.id = $ID 

/* build on this to get not blocked */ 
SELECT * 
FROM users u 
JOIN relationship r ON r.user_id = u.id 
JOIN relationship_block b ON b.user_id = u.id 
WHERE u.id = $ID 
    AND r.member_ID <> b.blocked_member_id 

/* get all users that NO ONE has blocked */ 
/* this means if there exists a record b such that b.blocked_member_id 
    equals the user X has blocked user Y, do not include user Y. 
    By extension, if X and Y are fierce enemies and have blocked eachother, 
    neither would get returned by the query */ 
SELECT * 
FROM users u 
JOIN relationship r ON r.id = u.id 
WHERE NOT EXISTS (SELECT null 
        FROM relationship_block rb 
        WHERE rb.blocked_member_id = u.id 
       ) 
/* This runs two queries at once. The inner query says "I'm not getting any 
    columns, because I don't care about the actual data, I just to get all 
    records where someone has blocked the user I'm currently looking for". 
    Then you select all users where that isn't true. For good speed, this would 
    require an index on relationship_block.blocked_member_id */ 
+0

作为一个侧面说明,不`SELECT *`...这是仅供参考! – corsiKa 2011-02-17 19:37:40