如何在MySQL中查询查询结果集?

时间:2014-03-28 02:13:54

标签: mysql sql

我需要在限定时间内获取重复记录

我的桌子是

id    designation     company     pdate            location
1     d1               c1         31-1-2014        delhi
2     d3               c1         2-2-2014         delhi
3     d5               c5         1-2-2014         chennai
4     d1               c1         12-2-2014        delhi
5     d2               c2         1-2-2014         chennai
6     d3               c1         2-2-2014         delhi
7     d3               c1         3-2-2014         delhi
8     d4               c2         2-2-2014         chennai
9     d5               c3         4-2-2014         delhi
10    d1               c4         5-2-2014         chennai
11    d1               c4         1-2-2014         delhi
12    d3               c1         2-2-2014         chennai
13    d2               c3         3-2-2014         delhi
14    d5               c5         1-2-2014         chennai

SELECT * FROM mytable WHERE pdate BETWEEN  '1-2-2014' AND  '2-2-2014'group by designation, company,location order by pdate ASC, designation ASC, company ASC, location ASC

现在我获取了记录

id    designation     company     pdate            location
3     d2               c2         1-2-2014         chennai
4     d3               c1         2-2-2014         delhi
8     d4               c2         2-2-2014         chennai
11    d1               c4         1-2-2014         delhi
12    d3               c1         2-2-2014         chennai
14    d5               c5         1-2-2014         chennai

现在对于每个提取的行,我必须在同一个表中查询重复(对于值指定,公司,位置)记录

所以我的最终输出将是

id    designation     company     pdate            location
2     d3               c1         2-2-2014         delhi
5     d2               c2         1-2-2014         chennai
6     d3               c1         2-2-2014         delhi
7     d3               c1         3-2-2014         delhi
8     d4               c2         2-2-2014         chennai
10    d1               c4         5-2-2014         chennai
12    d3               c1         2-2-2014         chennai
14    d5               c5         1-2-2014         chennai

因此,在我的最终结果中,我拥有日期1-2-2014到2-2-2014之间的所有值以及具有重复值的记录,公司,过滤日期记录中任何日期的位置

1 个答案:

答案 0 :(得分:0)

使用exists子句:

select t.*
from mytable t
where exists (SELECT *
              FROM mytable t2
              WHERE pdate BETWEEN '1-2-2014' AND '2-2-2014' and
                    t2.designation = t.designation and
                    t2.company = t.company and
                    t2.location = t.location
             );

你真的应该把你的日期常量放在YYYY-MM-DD的ISO标准格式中。