-3

コメントテーブル、ポストテーブル、ユーザーテーブル、および通知テーブルの 4 つのテーブルがあります。通知システムを構築したい。通知テーブルには次のものがあります

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

タイプは 1 または 2 のいずれかです。1 の場合はコメント、2 の場合は投稿です。

ユーザーのすべての通知を取得し、タイプに応じてコメントテーブル、ポストテーブルと結合する MySQL クエリを作成したいと考えています。たとえば、type が 1 で type id が 300 の場合、commmentable からコメント列を取得し、2 の場合は 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

$useridphp変数です

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 に答える