MySQL - GROUP By和DISTINCT,但返回所有行?

时间:2015-03-02 18:19:43

标签: mysql

自学习的初学者MySql ..我需要带回parent_ids匹配的所有行,但是年份没有。问题是,GROUP BY只为每个parent_id返回一行,我想要所有(所以,我一直在使用2个查询,并将结果从第一个粘贴到第二个)我如何在一个查询中执行此操作?

我有:

id  parent_id   year
aa1 aa          2010
aa3 aa          2011
bb1 bb          2010
bb2 bb          2011
cc1 cc          2010
cc2 cc          2010

我需要回复:

id  parent_id   year
aa1 aa          2010
aa3 aa          2011
bb1 bb          2010
bb2 bb          2011

当前第一个查询:

SELECT id, name, `year`, parent_id
FROM t1
GROUP BY parent_id
HAVING COUNT(DISTINCT `year`) > 1

然后我使用IN:

将结果粘贴到一个简单的选择查询中
SELECT id, parent_id, name, `year`
FROM t1
WHERE parent_id IN ('......',')

4 个答案:

答案 0 :(得分:1)

一个选项可能是使用子查询。例如:

SELECT id, name, year, parent_id
FROM t1
WHERE parent_id IN (SELECT parent_id
FROM t1
GROUP BY parent_id
HAVING COUNT(DISTINCT year) > 1)

如果要多次查询,您也可以使用视图。 http://www.w3schools.com/sql/sql_view.asp

答案 1 :(得分:1)

未启用ONLY_FULL_GROUP_BY模式时

SELECT id, parent_id, `year`
FROM test
GROUP BY parent_id, `year`
HAVING COUNT(*) = 1;

启用ONLY_FULL_GROUP_BY模式时

SELECT ANY_VALUE(id), parent_id, `year`
FROM test
GROUP BY parent_id, `year`
HAVING COUNT(*) = 1;

返回的结果是

+---------------+-----------+------+
| ANY_VALUE(id) | parent_id | year |
+---------------+-----------+------+
| aa1           | aa        | 2010 |
| aa3           | aa        | 2011 |
| bb1           | bb        | 2010 |
| bb2           | bb        | 2011 |
+---------------+-----------+------+

答案 2 :(得分:0)

SELECT  id, parent_id, year
    FROM  t1
    JOIN  
      ( SELECT  parent_id
            FROM  t1
            GROUP BY  parent_id
            HAVING  COUNT(DISTINCT year) > 1 ) AS b USING(parent_id
      );

(假设IN ( SELECT ... )被编入索引,JOIN比parent_id效率更高。)

或者您可能会发现GROUP_CONCAT更有趣:

SELECT  parent_id, GROUP_CONCAT(DISTINCT year) AS years
    FROM  t1;
    GROUP BY  parent_id
    HAVING  LENGTH(years) > 4; 

答案 3 :(得分:0)

尝试此查询:

select a.id , a.parent_id , a.year
from t1 a join t1 b
on a.id <> b.id and a.parent_id=b.parent_id and a.year<>b.year;