MySQL按计数选择发生

时间:2013-06-17 15:05:25

标签: mysql count

我有一个包含两列的表格,如下所示:

source_cid     inchikey
----------     --------
 1             qqmn
 2             qqmn
 3             ccmm

现在我想选择具有相同inchikeys的source_cids

这是我的问题:

SELECT source_cid, count(*) as c
FROM inchikey
GROUP BY inchikey HAVING count(*)>1

此代码永远运行。我该如何修改它?

2 个答案:

答案 0 :(得分:0)

尝试在table inchkey上创建重复索引(source_cid,inchikey),然后尝试运行查询:

SELECT inchikey, group_concat(distinct source_cid) source_cids, count(*) as c
FROM inchikey
GROUP BY inchikey HAVING count(distinct source_cid)>1

(您现有的查询只会为每个重复的inchikey显示一个source_cid。)

答案 1 :(得分:0)

首先,正如Anigel所说,我们需要查看你的创建语句,你应该使用索引。

其次,您的查询不会显示应显示的所有行。

请参阅:http://www.sqlfiddle.com/#!2/a810d/7

SELECT source_cid, count(*) as c
FROM inchikey
GROUP BY inchikey HAVING count(*)>1;

不幸的是,只输出带有source_cids 1的行。

select * from inchikey i,
(
SELECT i2.inchikey, count(i2.source_cid) as c
FROM inchikey i2
GROUP BY i2.inchikey HAVING count(i2.source_cid)>1
 ) as cd
where cd.inchikey = i.inchikey;

这样,输出1和2的行。