MySql - 三个成功连接表,但未能获得一列结果?

时间:2011-12-28 21:39:32

标签: php mysql html

我有三个表(用户,帖子,评论)加入(对于一个ajax驱动的社交网络我正在做的学位)。

到目前为止一直很好但是当我循环浏览它们时,除了一个之外我得到了所有结果。对帖子发表评论的人(存储在评论表中)的引用仅作为数字ID(应该加入用户表,但我的联接显然无法正常工作!)。

非常感谢任何帮助!可能很简单,因为我在这个PHP / mysql游戏中仍然是新手!

MySQL表:

           CREATE TABLE `post` (
           `pid` int(10) NOT NULL AUTO_INCREMENT,
           `uid` int(10) NOT NULL,
           `post` text NOT NULL,
           `pid_imageurl` varchar(100) NOT NULL,
           `likes` int(10) NOT NULL,
            PRIMARY KEY (`pid`)
            ) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 



           CREATE TABLE `user` (
           `uid` int(10) NOT NULL AUTO_INCREMENT,
           `name` varchar(20) NOT NULL,
           `password` varchar(20) NOT NULL,
           `uid_imageurl` varchar(100) NOT NULL,
           `joindate` varchar(11) NOT NULL,
           PRIMARY KEY (`uid`)
           ) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;


           CREATE TABLE `comments` (
           `cid` int(10) NOT NULL AUTO_INCREMENT,
           `comment_pid` int(10) NOT NULL,
           `comment_uid` int(10) NOT NULL,
           `comment` text NOT NULL,
            PRIMARY KEY (`cid`)
            ) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;

代码:

        $sql = "SELECT post.post, post.pid_imageurl, post.likes, user.name, comments.comment,   
        user.uid_imageurl, comments.comment_uid

                FROM post
                INNER JOIN user
                ON post.uid=user.uid
                LEFT JOIN comments
                ON comments.comment_pid=post.pid
                AND user.uid=comments.comment_uid
                ";

        $result = mysql_query($sql);



        while($row=mysql_fetch_assoc($result)){?>
        <ul>
            <li>User Profile image here:<? echo $row['uid_imageurl']; ?></li>
            <li>Post:<? echo $row['post']; ?></li>
            <li>Post by:<? echo $row['name']; ?></li>
            <li>Post images:<? echo $row['pid_imageurl']; ?></li>

            <li>post has: <? echo $row['likes']; ?> likes.</li>
            <li><? echo $row['comment']; ?></li>
            <li>by: <? echo $row['comment_uid']; ?></li>
           <!--This is only output as a stored id no rather than users name--!>




        </ul>


        <?}
        ?>

1 个答案:

答案 0 :(得分:0)

首先,您的查询应为:

SELECT 
    p.post, 
    p.pid_imageurl, 
    p.likes, 
    u.name, 
    c.comment,   
    u.uid_imageurl, 
    cu.name as CommentName
FROM 
    post p
    INNER JOIN user u ON 
        p.uid=u.uid
    LEFT JOIN comments c ON 
        c.comment_pid=post.pid
    left join user cu on
        c.comment_uid = cu.uid

$row['comment_uid']应该成为$row['CommentName']

您的原始查询只是抓取原始海报所做的评论(您的加入条件)。您想再次加入user表格以获取评论海报,而不是原始海报。