mysql - GROUP BY 列 HAVING COUNT(*) > 1,仍然显示所有行?

标签 mysql group-by group-concat

我只是想显示具有相同 GROUP_CONCAT() 列值的行。最后使用 GROUP BY 时,由于 GROUP BY 国家/地区,它只显示表中的最后一个全名。当我按国家/地区分组时是否仍然可以显示所有行? 这是我的 sql:

SELECT firstname, lastname, country, COUNT(*) c
FROM (
   SELECT firstname, lastname, 
   GROUP_CONCAT(
      DISTINCT f.countryname
      ORDER BY f.countryname ASC
      SEPARATOR ','
   ) AS country
   FROM person p 
   INNER JOIN favoritecountry f 
   ON p.id = f.id 
   GROUP BY firstname, lastname 
) t 
GROUP BY country 
HAVING c > 1
ORDER BY c DESC;

我的结果是:

+-----------+----------+--------------+---+
| firstname | lastname |   country    | c |
+-----------+----------+--------------+---+
| bill      | smith    | Poland,Spain | 2 |
+-----------+----------+--------------+---+

相反,我想要这样的东西:

+-----------+----------+--------------+---+
| firstname | lastname |   country    | c |
+-----------+----------+--------------+---+
| bill      | smith    | Poland,Spain | 2 |
| phil      | cooper   | Poland,Spain | 2 |
+-----------+----------+--------------+---+

SQL 新手,所以需要一些帮助

最佳答案

根据您的预期结果,您应该交叉加入 group_concat country 的计数和 country 的名称

    select  t2.firstname, t2.lastname, t2.country
    from   (
        SELECT firstname, lastname, 
        GROUP_CONCAT(
          DISTINCT f.countryname
          ORDER BY f.countryname ASC
          SEPARATOR ','
       ) AS country
       FROM person p 
       INNER JOIN favoritecountry f 
       ON p.id = f.id 
       GROUP BY firstname, lastname 
    ) t2
    cross join  (
        select t1.country, count(*) my_count
        from (
            SELECT firstname
             , lastname, 
            GROUP_CONCAT( DISTINCT f.countryname
                ORDER BY f.countryname ASC
                SEPARATOR ','
                ) AS country
            FROM person p 
            INNER JOIN favoritecountry f ON p.id = f.id 
            GROUP BY firstname, lastname 
        )   t 

    ) t1 on t1.country = t2.country

关于mysql - GROUP BY 列 HAVING COUNT(*) > 1,仍然显示所有行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54672115/

相关文章:

php - 在存储之前加密用户的 IP 地址

c# - Linq 中按元素分组

asp.net - 带条件的 SQL Group By

MySQL,反转 SELECT GROUP BY

php - 单个 select 语句中的多个 GROUP_CONCAT

MySQL GROUP_CONCAT DISTINCT 排序异常

mysql - 从子查询中选择

mysql - 如何使用mysql正确获取日期列当前日期的所有数据库

php - mySQL多查询解决方案

mysql - 检查是否超过 30 分钟