加入查询不起作用

时间:2010-05-31 13:14:02

标签: php mysql

我正在使用三个MySQl表:

评论

commentid loginid submissionid comment datecommented

登录

loginid username password email actcode disabled activated created points

提交

submissionid loginid title url displayurl datesubmitted

在这三个表中,“loginid”对应。

我想根据“submissionid”的数量拉出前10个登录名。我想将它们显示在一个3列HTML表格中,该表格显示第一列中的“用户名”,第二列中“submissionid”的数量,以及第三列中“commentid”的数量。

我尝试使用下面的查询,但它不起作用。知道为什么不呢?

提前致谢,

约翰

$sqlStr = "SELECT
                 l.username 
                 ,l.loginid  
                 ,c.commentid 
                 ,count(s.commentid) countComments
                 ,c.comment 
                 ,c.datecommented 
                 ,s.submissionid 
                 ,count(s.submissionid) countSubmissions
                 ,s.title
                 ,s.url 
                 ,s.displayurl 
                 ,s.datesubmitted
            FROM comment AS c
      INNER JOIN login AS l ON c.loginid = l.loginid
      INNER JOIN submission AS s ON c.loginid = s.loginid
        GROUP BY c.loginid
        ORDER BY countSubmissions DESC
           LIMIT 10";

  $result = mysql_query($sqlStr);

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

3 个答案:

答案 0 :(得分:1)

SELECT 
    l.loginid, 
    l.username, 
    COALESCE(s.total, 0) AS numSubmissions, 
    COALESCE(c.total, 0) AS numComments
FROM login l    
LEFT JOIN (
    SELECT loginid, COUNT(1) AS total 
    FROM submission 
    GROUP BY loginid
) s ON l.loginid = s.loginid
LEFT JOIN (
    SELECT loginid, COUNT(1) AS total 
    FROM comment 
    GROUP BY loginid
) c ON l.loginid = c.loginid
GROUP BY l.loginid
ORDER BY numComments DESC

答案 1 :(得分:1)

在您的查询中,您选择了非组项目,例如commentid,comment等。 这应该会产生预期的结果。

选择l.username,count(s.submissionid)为NoOfSubmissions,count(c.commentid)为NoOfComments from comment c INNER JOIN submission s ON c.submissionid = s.submissionid INNER JOIN登录l ON l.loginid = c.loginid group by l.username order by count(s.submissionid)limit 10;

谢谢,

Rinson KE DBA 91 + 9995044142 www.qburst.com

答案 2 :(得分:0)

select
 l.username,
 s.submissions,
 c.comments
from
 l,
 (
  select
   count(s.submissionid) as submissions,
   s.loginid
  from
   submission s
  group by
   s.loginid
 ) s,
 (
  select
   count(c.commentid) as commentids,
   c.loginid
  from
   comment c
  group by
   c.loginid
 ) c
where
 l.loginid = s.loginid and
 l.loginid = c.loginid
order by
 s.submissions desc
limit
 10