-3

我有四个表commenttable、posttable、usertable 和notifications 表。我想建立一个通知系统。通知表具有以下内容

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

类型可以是 1 或 2。如果为 1,则为评论,如果为 2,则为帖子。

我想构建一个 MySQL 查询,它获取用户的所有通知,并将它们与评论表、posttable 连接起来,具体取决于类型。例如,如果 type 是 1 并且 type id 是 300 那么它会从commmentable 中拉出评论列,如果它是 2 那么它会从 post 表中拉出 post 列。

post中的列如下:

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

1 回答 1

1

认为您的意思是进行外部联接,因为似乎通知不能同时适用于 posttable 和 commenttable

像这样的东西

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
于 2013-07-01T20:40:33.933 回答