在id上组合两列

时间:2012-03-06 15:54:02

标签: mysql

这是我的数据库

database schema http://slashdir.com/php/blogg/images/bloggdb.png

我想要做的是,对于给定的用户ID,显示他被报告的总时间。 我已经阅读了有关此事的各种其他问题,但我仍然感到难过。

我试过的最新查询是

select
   sum(posts.timesreported + comments.timesreported) AS total_reports
FROM 
  posts 
  INNER JOIN comments ON (posts.userid = comments.userid) 
WHERE posts.userid=5 AND comments.userid=5;

但这一定是错的,因为我得到的数字太高了

谢谢!

4 个答案:

答案 0 :(得分:2)

SELECT 
 CASE WHEN NULL
      THEN 0
      ELSE (select sum(posts.timesreported) AS total_posts_reports
            FROM  posts  INNER JOIN users ON (posts.userid = users.id) 
            WHERE posts.userid=5) 
      END 
 +
 CASE WHEN NULL
      THEN 0
      ELSE (select sum(comments.timesreported) AS total_comments_reports
            FROM  comments  INNER JOIN users ON (comments.userid = users.id) 
            WHERE comments.userid=5) 
      END
FROM DUAL; 

答案 1 :(得分:1)

而不是

sum(posts.timesreported + comments.timesreported) AS total_reports

sum(posts.timesreported) + sum(comments.timesreported) AS total_reports

我想你需要按userId分组

答案 2 :(得分:1)

看起来你收集的费用是先挑出用户。也许这是在加入之前为所有用户添加这些列值?如果SELECT *,在userID = 5的情况下执行INNER JOIN会发生什么。将列值保存为两个变量,然后尝试添加它们。你得到相同的结果吗?

这可能有助于您进行错误检查以确定上述理论是否准确。

            <?php 
             // Connects to your Database 
             mysql_connect("your.hostaddress.com", "username", "password") or die(mysql_error()); 
             mysql_select_db("Database_Name") or die(mysql_error());

             //Run Query
            $NUM1=mysql_query("SELECT Field1 FROM Table WHERE user.key=5");
            $NUM2=mysql_query("SELECT Field2 FROM Table WHERE user.key=5");

             //Print Each Result
            echo 'Num1 = '.$NUM1;
            echo 'Num2 = '.$NUM2;

             //Print Total
            $TOTAL = $NUM1 + $NUM2;
            echo 'Total = '.$TOTAL;
            ?>

答案 3 :(得分:1)

WHERE posts.userid=5 AND comments.userid=5;是不必要的,因为这些表是连接在一起的。

sum运算符在逻辑上不正确

使用此查询

select
   sum(posts.timesreported) + sum(comments.timesreported) AS total_reports
FROM 
  posts 
  INNER JOIN comments ON (posts.userid = comments.userid) 
WHERE posts.userid=5