合并2个SQL表中条目的总计数

时间:2011-07-17 10:29:56

标签: php mysql html sql count

我似乎无法找到正确的方法来做到这一点所以我希望有人可以给我一些方向?

SQL数据库的结构如下(我删除了不相关的东西):

Requests
R_ID    R_FulfilledBy
1       Bob
2       Craig
3       Bob

SIMs
SM_ID   SM_FulfilledBy
1       Bob
2       Craig
3       Bob

我希望最终得到这个输出:

Fulfilled By    Requests
Bob         4
Craig       2

这是我的PHP / HTML:

<div id="table">
        <?php

            //Connect to MySQL Database
            $connection = mysql_connect($runnerdbServer, $runnerdbUser, $runnerdbPass);
            mysql_select_db($runnerdbName, $connection) or die("MysQL Error");

                            $query = "SELECT R_FulfilledBy, COUNT(R_ID) FROM Requests GROUP BY R_FulfilledBy ORDER BY COUNT(R_ID) DESC"; 


                            $result = mysql_query($query) or die(mysql_error());



        ?>

    <!-- Number of Runners (Counts total number of records in Requests table) -->
    <table border='0' width='50%'>
        <tr>
        <th>Runners Fulfilled</th>
        <tr><td><?php
            $query = mysql_query("SELECT * FROM Requests");
            $number=mysql_num_rows($query);
            echo $number; 
            ?>
        </td></tr>
    </table>
    &nbsp;

    <!-- Fulfillment Stats -->
    <table border='0' width='50%'>
        <tr>
        <th>Name</th>
        <th>Runners Fulfilled</th>
        </tr>

    <?
    // Print out result (I want this to calculate requests fulfilled by each user in 'Requests' and 'SIMs' table)
    while($row = mysql_fetch_array($result)){
    echo "<tr>";
    echo "<td>". $row['R_FulfilledBy'] ."</td>";
    echo "<td>". $row['COUNT(R_ID)'] ."</td>";
    echo "</tr>";
    }

    ?>

    </table>

目前它只计算“请求”表中的记录:(

2 个答案:

答案 0 :(得分:4)

您可以在子查询中union all将两个表放在一起:

select  FulfilledBy
,       count(*)
from    (
        select  R_FulfilledBy as FulfilledBy
        from    Requests
        union all
        select  SM_FulfilledBy
        from    SIMs
        ) as SubQueryAlias
group by
        FulfilledBy

使用union all代替union,因为第二个消除了重复;这将使每个人的最大数量为1。

答案 1 :(得分:0)

我会这样做:

SELECT R_FulfilledBy, COUNT(*) + 
( SELECT COUNT(*) FROM SIMs WHERE R_FulfilledBy = SM_FulfilledBy )
FROM Requests GROUP BY R_FulfilledBy