2011-02-17 9 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