2013-07-01 46 views
-3

我有四張表commenttable,posttable,usertable和notifications表。我想建立一個通知系統。該通知表具有以下MYSQL JOIN查詢通知

column id, 
notifier, 
notifying, 
date, 
type, 
typeid 

類型可以是1或2。如果是1,這是一個註釋,如果是2,這是一個職位。

我想建立一個MySQL查詢,獲取用戶的所有通知,並根據類型將它們與註釋表,表格連接在一起。例如,如果type是1並且type id是300,那麼它將從可調整內容中提取評論列,如果它的值爲2,那麼它將從帖子表中提取帖子列。是

在後列如下:

postid, post and commenttable commenter, comment, commentid 

我已經建立了一個查詢,如下所示,但它不喜歡工作,我希望它

SELECT 
    notificationstable.who, 
    notificationstable.type, 
    notificationstable.timestamp, 
    notificationstable.date, 
    commenttable.comment, 
    commenttable.commentid, 
    usertable.username, 
    usertable.avatar, 
    usertable.userid, 
    usertable.verified, 
    posttable.photo, 
    posttable.title, 
    posttable.postid 
from 
    notificationstable 
     inner join 
    usertable 
     inner join 
    posttable 
     inner join 
    commenttable ON notificationstable.who = usertable.userid 
and posttable.postid = notificationstable.type 
and commenttable.commentid = notificationstable.type 
where 
    notificationstable.whom = '$userid' 
order by notificationstable.date desc 

$userid是PHP變量

+4

「這是行不通的像我希望它」是一個非常糟糕的問題說明,如果你想人來幫助你。 – PeeHaa

+0

它在做什麼不是你所期望的?你在期待什麼? – crush

+1

它給你什麼結果?你期望什麼結果。如果您要將表和一些數據放入SQL小提琴中供我們使用,那將會很有幫助。 –

回答

1

認爲你的意思是做外部連接,因爲它似乎是一個通知不能適用於郵寄表和評論表

像這樣的事情

SELECT 
    notificationstable.who, 
    notificationstable.type, 
    notificationstable.timestamp, 
    notificationstable.date, 
    commenttable.comment, 
    commenttable.commentid, 
    usertable.username, 
    usertable.avatar, 
    usertable.userid, 
    usertable.verified, 
    posttable.photo, 
    posttable.title, 
    posttable.postid 
FROM notificationstable 
INNER JOIN usertable 
ON notificationstable.who = usertable.userid 
LEFT OUTER JOIN posttable 
ON posttable.postid = notificationstable.type 
LEFT OUTER JOIN commenttable 
ON commenttable.commentid = notificationstable.type 
WHERE notificationstable.whom = '$userid' 
ORDER BY notificationstable.date DESC 
+0

從OP的帖子,我不知道它應該是什麼,但我認爲'posttable.postid = notificationstable.type'是一個問題。他說這個類型是1或2,如果它是1,你應該執行一個註釋表查詢或2你應該執行一個表格查詢。我認爲'OUTER JOIN commenttable ON ON commenttable.commentid = notificationstable.whatever_the_heck_the_column_name_corresponding_to_the_comment_or_post_id_is'就是主意。 –

+0

我不是MYSQL忍者,但你可以這樣做:'... CASE WHEN notificationstable.type = 1 THEN INNER JOIN commenttable ON ON commenttable.commentid = notificationstable。still_need_this_column ELSE INNER JOIN posttable ON posttable.postid = notificationstable.still_need_this_column'並可能與select做類似的事情? –

+0

我認爲你可能是對的,但很難從原文中明確。我已經採取了他的查詢(沒有嘗試使用它),並將其修改爲使用外部連接。如果通知類型定義了是發佈表還是評論表,那麼使用內部聯接,則兩者不能同時匹配帖子和評論。您可以執行LEFT JOIN,然後使用CASE(或只是一個IF)來定義哪些表列將作爲特定列返回。 – Kickstart