2013-04-02 21 views
1

我有3個表格,tbl_topic,tbl_comment,tbl_user。 我想選擇用戶創建的所有主題,以及即使他不是創建者也評論過的主題。這裏是我的數據庫:如何加入3個表格,主題,評論和用戶

tbl_topic 
---------- 
topic_id 
topic_title 
user_id 

tbl_comment 
---------- 
comment_id 
comment_message 
user_id 
topic_id 

tbl_user 
---------- 
user_id 
user_name 

需要它如此糟糕。謝謝!

到目前爲止,我得到這個

select * from tbl_topic T inner join tbl_comment C on T.topic_id = C.topic_id inner join tbl_user U on T.user_id = U.user_id GROUP BY T.topic_id 

我的問題是它只返回上有評論的主題。我想包含用戶創建的主題,即使它有0條評論。

我想要的結果是這樣的:

+-----------+-----------+----------+-------------+----------------+----------+------- 
    | topic_id | topic_title | user_id | comment_id | comment_message | user_id | topic_id | 
    +-----------+-----------+----------+-------------+----------------+----------+-------- 
    | 1   | my topic | 1  | 1   | comment me  | 1  | 1 
    | 2   | others | 2  | 2   | comment me  | 1  | 2 
    | 3   | my nocoment| 1  | NULL  | NULL   | NULL | NULL 
    +-----------+---------+--------+-------------+----------+----------+---------+-------- 

    ----------+-----------+ 
     user_id | user_name | 
     -----------+----------- 
     1   | me  | 
     2   | someone | 
     1   | me 
     -----------+---------+-- 

我在表搞砸我的領域,comment_message旁邊的USER_ID應comment_user_id但我已經創建了數據庫的方式。你能幫助做到這一點嗎?

+3

更好的貼你已經嘗試過..! – goseo

+0

你指的是用戶完成的活動,我是對嗎? –

+0

如果出現這種情況,您必須使用左外連接進行評論,然後使用UNION進行活動。 –

回答

2

以下查詢在子查詢中使用UNION第一個SELECT獲取用戶創建的所有主題。 SELECT聲明獲取用戶的所有評論並將其加入表tbl_topic,因此我們可以獲得topic_title

SELECT topic_ID, topic_title 
FROM 
     (
      SELECT a.user_ID, b.topic_ID, b.topic_title 
      FROM tbl_user a 
        INNER JOIN tbl_topic b 
         ON a.user_ID = b.user_ID 
      UNION 
      SELECT a.user_ID, c.topic_ID, c.topic_title 
      FROM tbl_user a 
        INNER JOIN tbl_comment b 
         ON a.user_ID = b.user_ID 
        INNER JOIN tbl_topic c 
         ON b.topic_ID = c.topic_ID 
     ) x 
WHERE x.user_ID = ? 
+1

這就更像了。:) +1 –

+0

先生,請參閱更新?如果用戶有帖子並且沒有評論會怎麼樣?我認爲你必須使用外部連接。 –

+1

@BlackHatShadow這就是我使用'UNION'的原因。這也可以使用外部連接來完成,但仍然需要一個子查詢。 –

0

請嘗試以下的查詢。這將顯示所有的字段。

SELECT tt.*, tc.*, tbl_user.* 
FROM tbl_topic AS tt INNER JOIN tbl_comment AS tc ON tt.topic_id = tc.topic_id INNER JOIN tbl_user as tc ON tc.user_id = tu.user_id; 
WHERE tu.user_id = x 

如果必須過濾添加到查詢的WHERE子句。

+1

不要忘記添加一個WHERE user_id = x :) – Ponsjuh

+0

感謝您指出。 – Techie

0

繼續左加入。但還有一個問題,你只會得到一個表評論和一個用戶。爲了獲得更多的,你可以使用GROUP_CONCAT功能,喜歡這裏:http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat

select * from tbl_topic T 
    LEFT JOIN tbl_comment C on T.topic_id = C.topic_id 
    LEFT join tbl_user U on T.user_id = U.user_id 
WHERE T.user_id = x 
GROUP BY T.topic_id 

編輯:where子句失蹤

+0

這將如何解決問題?這將返回所有可用的主題,無論用戶是否已創建。 –

+0

編輯我的答案。剛剛錯過了這一點。 – Argeman