查询在一个表中查找注释,在另一个表中查找用户名

时间:2010-04-05 19:00:51

标签: php mysql

我正在使用名为“login”的MySQL表,其结构如下:

loginid, username, password, email, actcode, disabled, activated, created, points

我正在使用另一个名为“comment”的MySQL表,其结构如下:

commentid, loginid, submissionid, comment, datecommented

对于给定的“submisssionid”,我想从“评论”表中打印出以下信息:

- 字段“comment”和“datecommented”。

同时,我想从“登录”表中打印出以下内容:

- 对应于从“评论”表中选择的每一行的“loginid”的“用户名”。

我该怎么做?

我尝试了下面的代码,但它没有用。

提前致谢,

约翰

$submission = mysql_real_escape_string($_GET['submission']);
$submissionid = mysql_real_escape_string($_GET['submissionid']);


    $sqlStr = "SELECT 
                    c.loginid
                    ,c.submissionid
                    ,c.comment
                    ,c.datecommented
                    ,l.username
                    ,COUNT(c.commentid) countComments
                 FROM 
                    comment c
                WHERE
                    c.submissionid = $submissionid  
                INNER
                 JOIN
                    login l
                   ON
                    c.loginid = l.loginid
                 GROUP
                    BY
                     c.submissionid
                 ORDER  
                    BY 
                     c.datecommented DESC
                 LIMIT 
                     100";          

    $result = mysql_query($sqlStr);

    $arr = array(); 
    echo "<table class=\"samplesrec\">";
    while ($row = mysql_fetch_array($result)) { 
        echo '<tr>';
        echo '<td class="sitename1">'.$row["comment"].'</td>';
        echo '</tr>';
        echo '<tr>';
        echo '<td class="sitename2"><a href="http://www...com/sandbox/members/index.php?profile='.$row["username"].'">'.$row["username"].'</a>'.$row["datecommented"].'</td>';
        echo '</tr>';
        }
    echo "</table>";    

1 个答案:

答案 0 :(得分:0)

SELECT comment.comment, comment.datecommented, login.username
FROM comment
LEFT JOIN login ON comment.loginid=login.loginid
WHERE submissionid=$submissionid
ORDER BY comment.datecommented DESC 
LIMIT 100";