如果没有要匹配的条件的行要在第二个表中计数,如何显示一个表中的所有行

时间:2019-05-21 22:42:56

标签: php mysql join count

我有两个桌子。 “成员”是所有成员的列表,“统计”是工作日期的列表。共享字段是memberID。我需要每个人工作的天数COUNT,并且我希望每个人都在输出表中列出,即使他们还没有工作一天。

简化的数据库结构是:

**members**                 **stats**       
memberID lname    fname     memberID    date    statsID
1        Mertz    Fred      1        2017-12-31    1
2        Doe      Jane      3        2017-12-31    2
3        Smith    Frank     4        2017-12-31    3
4        Ricardo  Lucy      2        2018-12-31    4
5        Starr    Ringo     4        2018-12-31    5
                            2        2019-05-05    6
                            3        2019-05-05    7

所需的输出是:

memberID  lname  fname  Total Days 
2         Doe    Jane       2 
1         Mertz  Fred       1 
4         Ricardo Lucy      2 
3         Smith   Frank     2 
5         Starr   Ringo     0 OR blank

Ringo尚未使用任何天,并且不会出现在输出表中。

我的代码是:

$sql = "SELECT  u.*,
   COUNT(s.memberID)as tot_days
   FROM members u
   LEFT JOIN stats s
    ON s.memberID = u.memberID 
    GROUP BY s.memberID
    ORDER BY lname,fname";

$members = mysqli_query($dbc,$sql) or die(mysqli_error());

while ($row = mysqli_fetch_array($members)){ 
        $row = array_map('htmlspecialchars', $row);
        echo <<< HTML  etc.

这可以做我想做的所有事情,除了那些还没有一天工作的成员。联接,左联接,左外联接,右联接,右外联接都产生相同的结果。我尝试了LEFT和RIGHT INNER JOIN(如果存在),它们产生了错误Warning: mysqli_error() expects exactly 1 parameter, 0 given

有人建议使用COALESCE (COUNT(s.memberID),0) as tot_days,但这只会产生与上述相同的错误。

我已经待了好几天了,变得有点沮丧!

2 个答案:

答案 0 :(得分:1)

SELECT u.*
     , COUNT(DISTINCT s.date) tot_days
  FROM members u
  LEFT 
  JOIN stats s
    ON s.memberID = u.memberID
 GROUP 
    BY u.memberID
 ORDER 
    BY u.lname
     , u.fname

答案 1 :(得分:-1)

您将不得不重新构造您的查询

create table members (id int primary key auto_increment, lname varchar(30), fname varchar(30));
insert into members values (1, 'Mertz',   'Fred') ,(2, 'Doe',     'Jane') ,(3, 'Smith',   'Frank'),(4, 'Ricardo', 'Lucy') ,(5, 'Starr',   'Ringo');


create table stats (member_id int, dates date, stat_id int);
insert into stats values (1, '2017-12-31', 1),(3, '2017-12-31', 2),(4, '2017-12-31', 3),(2, '2018-12-31', 4),(4, '2018-12-31', 5),(2, '2019-05-05', 6),(3, '2019-05-05', 7);



mysql> (select 
    -> m.id,
    -> m.fname,
    -> count(*) as total_days
    -> from 
    -> members m inner join stats s on m.id = s.member_id
    -> group by m.id)
    -> union
    -> (select
    -> m.id,
    -> m.fname,
    -> 0 as total_days
    -> from
    -> members m where not exists ( select * from stats s where m.id = s.member_id));
+----+-------+------------+
| id | fname | total_days |
+----+-------+------------+
|  1 | Fred  |          1 |
|  3 | Frank |          2 |
|  4 | Lucy  |          2 |
|  2 | Jane  |          2 |
|  5 | Ringo |          0 |
+----+-------+------------+
5 rows in set (0.00 sec)