自我加入独特的行?

时间:2010-08-04 10:53:00

标签: mysql

select * from hari;
+------+------------+-------+
| id   | mydate     | email |
+------+------------+-------+
|    1 | 2009-10-10 | 1111  | 
|    1 | 2009-10-10 | 1111  | 
|    1 | 2009-10-10 | 2222  | 
|    2 | 2010-11-11 | 3333  | 
|    2 | 2010-11-11 | 3333  | 
+------+------------+-------+
5 rows in set (0.01 sec)

按ID,mydate和电子邮件分组后,只有2条记录,数学ID = 1 我该怎么做?

有人给了我以下查询,其中第一个ID的计数是2(正确) 但我发现这个问题非常混乱,并且猜测必须有更好的方法。

mysql>SELECT
count(sel2.refid2 ) as recCount,
refid2, recDate2
FROM
(SELECT id AS refid2, mydate AS recDate2
FROM hari AS ol_Email1
GROUP BY ol_Email1.id, ol_Email1.mydate, ol_Email1.email 
) AS sel2
GROUP BY sel2.refid2
+----------+--------+------------+
| recCount | refid2 | recDate2   |
+----------+--------+------------+
|        2 |      1 | 2009-10-10 | 
|        1 |      2 | 2010-11-11 | 
+----------+--------+------------+
2 rows in set (0.28 sec)

CREATE TABLE `hari` (
  `id` int(11) default NULL,
  `mydate` date default NULL,
  `email` varchar(100) default NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
INSERT INTO `hari` VALUES (1,'2009-10-10','1111'),(1,'2009-10-10','1111'),(1,'2009-10-10','2222'),(2,'2010-11-11','3333'),(2,'2010-11-11','3333');

2 个答案:

答案 0 :(得分:1)

SELECT * FROM hari WHERE id = 1 GROUP BY email 

答案 1 :(得分:1)

像...一样的东西。

SELECT *,
       COUNT(*)
    FROM hari
    GROUP BY id, mydate, email;

(我不太确定你要分组哪些列)