具有相同多列

时间:2016-09-15 08:07:44

标签: mysql sql

我是SQL新手。我想要一个返回具有多个共同列

的值的查询

我有t_table:

           filename               |    start            |    stop
 AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA | 2016-12-24 00:00:00 | 2016-01-03 00:00:00
 AAAAAAAAAAAAAAAABBBBBBBBBBBBBBBB | 2016-12-24 00:00:00 | 2016-01-03 00:00:00
 CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC | 2016-12-24 00:00:00 | 2016-01-03 00:00:00

我想返回带有start和stop列的文件名,名称就像'%AAAA%' (第2行) CCCC%具有相同的开始和结束但名称不像'%AAAA%

我已尝试过这些答案Find rows that have the same value on a column in MySQL,但我无法获得预期的结果。随着:

SELECT  filename ,
        start
FROM    t_table
WHERE   ( start IN ( SELECT start
                     FROM   t_table
                     GROUP BY start
                     HAVING COUNT(*) > 1 ) )
        AND ( filename LIKE '%AAAA%' );

我已经获得了所有这些......

           filename               |    start            |    stop
 AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA | 2016-12-24 00:00:00 | 2016-01-03 00:00:00
 AAAAAAAAAAAAAAAABBBBBBBBBBBBBBBB | 2016-12-24 00:00:00 | 2016-01-03 00:00:00
 CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC | 2016-12-24 00:00:00 | 2016-01-03 00:00:00

而不是:

           filename               |    start            |    stop
 AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA | 2016-12-24 00:00:00 | 2016-01-03 00:00:00
 AAAAAAAAAAAAAAAABBBBBBBBBBBBBBBB | 2016-12-24 00:00:00 | 2016-01-03 00:00:00

你能帮我吗?

1 个答案:

答案 0 :(得分:3)

SELECT t1.filename,
       t1.start,
       t1.stop
FROM t_table t1
INNER JOIN
(
    SELECT start, stop            -- this subquery identifies all start, stop
    FROM t_table                  -- pairs for which 2 or more records share
    GROUP BY start, stop          -- those values
    HAVING COUNT(*) > 1
) t2
    ON t1.start = t2.start AND
       t1.stop  = t2.stop
WHERE t1.filename LIKE '%AAAA%'   -- filename contains 'AAAA'

在这里演示:

SQLFiddle