使用group by计算行数并显示所有行MYSQL PHP

时间:2016-11-08 08:55:54

标签: mysql sql count group-by

我有一个像这样的SQL表:

id     fname     cat                  address        status

1      Bash      Wedding venue        ABC            a
2      Bash      Wedding venue        BCD            a
3      jash      Wedding venue        ABC            a
4      hash      Wedding venue        BCD            a   
5      Rash      Wedding card         BCD            a

我想获取具有cat值婚礼场地的所有结果并计算重复的fname。我正在使用的查询就是这个,它的工作正常。

SELECT *, count(*) as counts
from table
where cat='Wedding venue' AND status='a'
Group by fname;

输出:

id     fname   count(*)     cat                address      status
1      Bash    2            Wedding Venue      ABC          a
3      jash    1            Wedding Venue      ABC          a
4      hash    1            Wedding Venue      BCD          a

有没有办法显示这样的输出:

id     fname   count(*)     cat                address      status
1      Bash    2            Wedding Venue      ABC          a
2      Bash    2            Wedding Venue      BCD          a
3      jash    1            Wedding Venue      ABC          a
4      hash    1            Wedding Venue      BCD          a

2 个答案:

答案 0 :(得分:1)

我们对“工作正常”有不同的定义,所以对我来说帮助可能有点棘手。

但是这样的查询可以获得您之后的结果。

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,fname VARCHAR(12) NOT NULL
,cat VARCHAR(20) NOT NULL
,address VARCHAR(12) NOT NULL
,status CHAR(1) NOT NULL
);

INSERT INTO my_table VALUES
(1,'Bash','Wedding venue','ABC','a'),
(2,'Bash','Wedding venue','BCD','a'),
(3,'jash','Wedding venue','ABC','a'),
(4,'hash','Wedding venue','BCD','a'),
(5,'Rash','Wedding card','BCD','a');

SELECT x.*
     , y.count 
  FROM my_table x 
  JOIN 
     ( SELECT fname
            , cat
            , status
            , COUNT(*) count 
         FROM my_table 
        GROUP 
           BY fname
            , cat
            , status
     ) y 
    ON y.fname = x.fname 
   AND y.cat = x.cat 
   AND y.status = x.status 
 WHERE x.cat = 'Wedding venue' 
   AND x.status = 'a';
+----+-------+---------------+---------+--------+-------+
| id | fname | cat           | address | status | count |
+----+-------+---------------+---------+--------+-------+
|  1 | Bash  | Wedding venue | ABC     | a      |     2 |
|  2 | Bash  | Wedding venue | BCD     | a      |     2 |
|  3 | jash  | Wedding venue | ABC     | a      |     1 |
|  4 | hash  | Wedding venue | BCD     | a      |     1 |
+----+-------+---------------+---------+--------+-------+

答案 1 :(得分:0)

您可以使用相关的子查询来计算相同fnames的数量:

SELECT t1.*, (select count(*) from table t2
              where t2.fname = t1.fname) as counts 
from table t1
where cat='Wedding venue' AND status='a'