如何计算具有相同值但ID不同的行

时间:2018-08-17 03:01:19

标签: php mysql count union

我已经在使用COUNT和UNION ALL的数据库中使用了此sql语句

SELECT tem.book_id, COUNT( * )
    FROM(SELECT book_id FROM borrowdetails
    WHERE borrowdetails.borrow_status = 'returned'
    UNION ALL
    SELECT book_id from reserve) as tem
    GROUP BY book_id
    ORDER BY book_id DESC

然后我使用此代码在PHP表中命名ID

while($row=mysql_fetch_array($user_query)){
    $id=$row['book_id'];
    $book_query = mysql_query("select * from book where book_id = '$id'")or die(mysql_error());
}

它可以正常工作,但不会将具有相同名称的数据合并在一起,因为它具有不同的ID,例如

+------+------+-------+
|  id  | name | count |
+------+------+-------+
|1     |A     |   3   | the id here is not shown at the table in PHP just   
+------+------+-------+ inside the database but the A is duplicate.
|2     |A     |   1   |
+------+------+-------+
|3     |B     |   2   |
+------+------+-------+

我想要的输出应该是这样的,表中没有显示ID。

+------+-------+
| name | count |
+------+-------+
|A     |   4   |
+------+-------+ this is the table that should be shown in PHP
|B     |   2   |
+------+-------+

您可能会看到名称A的个数变为4,因为我还想添加两个A的COUNT(*)。

我要做什么才能达到预期的结果?

这是所使用的数据库表。

+------+------+     +---------+---------+       +-------+-------+   
|  book table |     |borrowdetails table|       | reserve table |   
+------+------+     +---------+---------+       +-------+-------+   
|  id  | name |     |brw_dt_id| book_id |       |res_id |book_id|
+------+------+     +---------+---------+       +-------+-------+   
|1     |A     |     |    1    |    2    |       |   1   |   1   |
+------+------+     +---------+---------+       +-------+-------+
|2     |A     |     |    2    |    3    |       |   2   |   1   |
+------+------+     +---------+---------+       +-------+-------+
|3     |B     |     |    3    |    3    |       |   3   |   1   |
+------+------+     +---------+---------+       +-------+-------+

2 个答案:

答案 0 :(得分:0)

您想使用book_name而不是book_id。 我没有尝试过,但是应该可以

Select book_name, count(*) as cnt from books
where book_id IN (
     SELECT book_id FROM borrowdetails
     WHERE borrowdetails.borrow_status = 'returned'
     UNION ALL
     SELECT book_id from reserve
     )
GROUP BY Book_Name
ORDER BY Cnt

答案 1 :(得分:0)

我们通常会这样写

SELECT book_name
     , count(*) cnt 
  FROM books x
  JOIN
     ( SELECT book_id 
       FROM borrowdetails
      WHERE borrowdetails.borrow_status = 'returned'
      UNION ALL
      SELECT book_id from reserve
     ) y
  ON y.book_id = x.book_id
 GROUP BY Book_Name -- this assumes that book_name is unique 
  ORDER BY Cnt