MySQL计数cccurrence并加入同一个表

时间:2014-10-11 07:04:50

标签: mysql count inner-join

我有以下表格数据:

ID DrawDate    DrawNumber
1  01/01/2014  1234
2  01/01/2014  1235
3  01/01/2014  1236
4  02/01/2014  1237
5  02/01/2014  1234
6  02/01/2014  1238
7  03/01/2014  1234
8  03/01/2014  1235
9  03/01/2014  1239

我想MySQL计算DrawNumber的出现次数,并将结果填充回来显示如下:

ID DrawDate    DrawNumber Occuurence
1  01/01/2014  1234       3
2  01/01/2014  1235       2
3  01/01/2014  1236       1
4  02/01/2014  1237       1
5  02/01/2014  1234       3
6  02/01/2014  1238       1
7  03/01/2014  1234       3
8  03/01/2014  1235       2
9  03/01/2014  1239       1

我设法获得了以下MYSQL代码,但似乎它将现有数据库的总记录翻了一倍。

SELECT
DISTINCT table.ID, table.DrawDATE,table.DrawNumber.
(SELECT
COUNT(table.ID)
FROM table
WHERE table1.DrawNumber = table.DrawNumber
) AS Occuurence

FROM table
INNER JOIN table AS table1 ON table.DrawNumber = table1.DrawNumber
ORDER BY table.DrawDATE DESC

任何人都可以建议更好的MySQL查询?

提前致谢。

CK

2 个答案:

答案 0 :(得分:0)

尝试以下:

SELECT
DISTINCT a.ID, a.DrawDATE,a.DrawNumber,count(a.DrawNumber) as occurance
(select *  FROM table
ORDER BY table.DrawDATE DESC)a group by a.DrawNumber

如果你不想使用group by,如果你想在输出中保存相同数量的记录,那么你可以尝试下面的查询:

SELECT
DISTINCT table.ID, table.DrawDATE,table.DrawNumber.
(SELECT
COUNT(table.ID)
FROM table
WHERE table1.DrawNumber = table.DrawNumber
) AS Occuurence

FROM table
ORDER BY table.DrawDATE DESC

答案 1 :(得分:0)

感谢Ronak Shah回答。

我使用另一种方法,在其中我创建一个视图来获取计数结果然后加入表。它工作正常。